假设我想插入一条评论,评论表需要一个customer_id
,但我只有email
。我不想事先在单独的查询中选择客户。
来自INSERT INTO ... SELECT
/query-builder.html#inserting-data的查询看起来正是我想要的。
但是我如何提供在查询的第一部分中选择的值之外的值呢?
1.我试探着:
$select = $customersTable->find()
->select(['customer_id'])
->where(['email' => '[email protected]']);
$query = $this->query()
->insert(['customer_id', 'data'])
->values($select)
->values(['data' => 'test 123'])
->execute();
字符串
我得到了:* 你不能在插入中混合子查询和数组数据 *
1.我试探着:
$select = $customersTable->find()
->select(['customer_id', '"test" AS `data`'])
->where(['email' => 'username@example']);
$query = $this->query()
->insert(['customer_id', 'data'])
->values($select)
->execute();
型
我得到了:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`` AS `Customers__"test" AS `data`` FROM `customer` `Customers` ' at line 1
INSERT INTO `comments` (`customer_id`, `data`) SELECT `Customers`.`customer_id` AS `Customers__customer_id`, `Customers."test" AS `data`` AS `Customers__"test" AS `data`` FROM `customer` `Customers` WHERE `email` = :c0
型
请帮
1条答案
按热度按时间aurhwmvo1#
SELECT
子句中的自定义别名字段可以通过常规key => value
数组语法定义,其中键将用作别名。还要确保让驱动程序引用数据,因为它将按原样插入,否则很容易发生SQL注入!
字符串
另见
*Cookbook > Database Access & ORM > Query Builder > Selecting Data