假设我想插入评论,评论表需要一个
customer_id
,但我只有email
。我不想事先在单独的查询中选择客户。
来自
orm/query-builder.html#inserting-data的
INSERT INTO ... SELECT
查询看起来正是我想要的。
但是如何提供查询第一部分中选择的值之外的值?
我试过:
$select = $customersTable->find()
->select(['customer_id'])
->where(['email' => '[email protected]']);
$query = $this->query()
->insert(['customer_id', 'data'])
->values($select)
->values(['data' => 'test 123'])
->execute();
我得到:你不能在插入中混合子查询和数组数据
我试过:
$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
请帮忙
SELECT
子句中的自定义别名字段可以通过常规key => value
数组语法定义,其中键将用作别名。
还要确保让驱动程序引用数据,因为它将按原样插入,否则很容易出现 SQL 注入!
$select = $customersTable->find()
->select([
'customer_id',
'data' => $customersTable->getConnection()->quote('test')
])
->where(['email' => 'username@example']);
另请参阅