我需要为Laravel转换此查询,并且在尝试创建插入时遇到问题...使用Laravel的Eloquont ORM或查询的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
如何使用Laravel的ORM创建此查询?
编辑:我不确定这是否清楚,但我考虑的是1个查询,就像他们这里的http://dev.mysql.com/doc/refman/5.0/en/insert-select.html一样。
发布于 2015-11-26 23:47:12
您可以使用:
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]);
发布于 2019-04-16 03:55:14
我使用了DB::statement("...");
DB::statement("INSERT INTO table (SELECT)");
发布于 2018-08-09 13:50:45
在Laravel 5.5中,我创建了一个帮助函数,以便更容易地执行:
class QueryHelper
{
/**
* @param string $model
* @param array $columns
* @param Builder $select
* @return bool
*/
public static function insertFromSelectStatement($model, $columns, $select)
{
/** @var \Illuminate\Database\Query\Builder $query */
$query = (new $model)->getQuery();
$sql = "insert into {$query->from} (". implode(', ', $columns) .") {$select->toSql()}";
return $query->getConnection()->insert($sql, $select->getBindings());
}
}
例如:
$notification = Notification::create([
'title' => 'this is title',
'message' => 'this is message',
]);
$now = DB::raw("'". Carbon::now()->toDateTimeString() ."'");
$selectActivatedUsers = User::select('id', $notification->id, $now, $now)->where('status', '=', 'activated');
// insert notifications to activated users
QueryHelper::insertFromSelectStatement(UserNotification::class, ['user_id', 'notification_id', 'created_at', 'updated_at'], $selectActivatedUser);
https://stackoverflow.com/questions/25533608
复制相似问题