在Laravel中创建一个Insert ... Select语句

jam*_*dri 19 php mysql laravel

我需要将此查询转换为Laravel,并且我在尝试使用Laravel的Eloquont ORM或Queries创建Insert ... Select语句时遇到问题.我不确定如何创建此查询.

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
Run Code Online (Sandbox Code Playgroud)

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

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

chi*_*lli 39

在一个查询中无法做到这一点,但我遇到了同样的问题,并希望确保我可以继续使用我使用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, Laravel is a little
 * stupid here
 */
 $insertQuery = 'INSERT into user_debt_collection (email,dinero) '
                . $select->toSql();

 \DB::insert($insertQuery, $bindings);
Run Code Online (Sandbox Code Playgroud)

  • 这真是太棒了。 (2认同)
  • 使用Laravel 5.7,您可以使用以下方法简化操作:`DB :: table('user_debt_collection')-> insertUsing(['email','dinero'],$ select);` (2认同)

小智 11

您可以使用:

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]);
Run Code Online (Sandbox Code Playgroud)