php Yii2中如何编写插入查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30068624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write Insert Query in Yii2?
提问by Kalai S
In Yii2 How to insert data from one table to another table.
在 Yii2 中如何将数据从一张表插入到另一张表。
Here i have two tables table1
and table2
.
这里我有两张桌子table1
和table2
。
Now what i need is when a condition met i need transfer a specific data from table1
to table2
.
现在我需要的是,当满足条件时,我需要将特定数据从table1
to传输table2
。
so help to write insert Query for this scenario in Yii2
所以帮助在 Yii2 中为这个场景编写插入查询
This is the insert query given in yii2 docs
这是 yii2 文档中给出的插入查询
Yii::$app->db->createCommand()
->insert('user', [
'name' => 'Sam',
'age' => 30,
])->execute();
But i need this Query to be convert according Yii2 Query
但是我需要根据 Yii2 Query 转换这个 Query
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers;
回答by arogachev
QueryBuilder
's insert
method returns this:
QueryBuilder
的insert
方法返回这个:
return 'INSERT INTO ' . $schema->quoteTableName($table)
. ' (' . implode(', ', $names) . ') VALUES ('
. implode(', ', $placeholders) . ')';
So there is no way to specify SELECT
here.
所以这里没有办法指定SELECT
。
Can't find it in core, I thinks it's not implemented because it's pretty rare case.
在核心中找不到它,我认为它没有实现,因为这是非常罕见的情况。
You can use your custom SQL code like this:
您可以像这样使用自定义 SQL 代码:
$sql = '...';
\Yii::$app->db->createCommand($sql)->execute();
Useful links:
有用的链接:
P.S.I also reported issue here, so maybe it will be added to the core in the future. If you want it now for repeated usage, you can implement such method by yourself.
PS我也在这里报告了问题,所以也许将来它会被添加到核心中。如果你现在想要重复使用,你可以自己实现这样的方法。