创建插入...在拉拉维尔中选择语句

2022-08-30 15:05:47

我需要将此查询转换为Laravel,并且在尝试创建插入时遇到了问题...使用Laravel的Eloquont ORM或Quelses选择语句。我不确定如何创建此查询。

Insert into Demand (Login, Name, ApptTime, Phone, Physician, Location, FormatName, FormatDate, FormatTime, ApptDate, FormatPhone, cellphone)
Select Login, Name, ApptTime, Phone, Physician, Location, FormatName, FormatDate, FormatTime, ApptDate, FormatPhone, cellphone from " . [dbname] . "
    Where " . $where_statement

如何使用Laravel的ORM创建此查询?

编辑:我不确定这是否清楚,但我正在考虑1查询,就像他们在这里所做的那样 http://dev.mysql.com/doc/refman/5.0/en/insert-select.html


答案 1

没有办法在一个查询中执行此操作(除非您使用的是Laravel 5.7),但是我遇到了同样的问题,并希望确保我可以继续使用我使用QueryBuilder构建的某个选择。

因此,您可以做的是,保持一半的干净,并重用之前构建过select语句的功能,是这样的:

/**
 * Wherever your Select may come from
 **/
$select = User::where(...)
                  ->where(...)
                  ->whereIn(...)
                  ->select(array('email','moneyOwing'));
/**
 * get the binding parameters
 **/ 
$bindings = $select->getBindings();
/**
 * now go down to the "Network Layer"
 * and do a hard coded select
 */
 $insertQuery = 'INSERT into user_debt_collection (email,dinero) '
                . $select->toSql();
    
 \DB::insert($insertQuery, $bindings);

更新拉拉维尔 5.7

从 Laravel 5.7.17 开始,您可以使用 ->insertUsing()。有关详细信息,请参阅此处。感谢@Soulriser指出这一点。

所以上面的查询将如下所示:

DB::table('user_debt_collection')->insertUsing(['email','dinero'], $select);

答案 2

您可以使用:

DB::insert("insert into contacts(contact_id,contact_type,account_id,created_at,updated_at) select f.id,'App\\Friend',f.account_id,f.created_at,f.updated_at from friends as f where f.id=?",[16]);

推荐