I\'m needing to convert this query for Laravel and I\'m having issues trying to create an Insert... Select statement using Laravel\'s Eloquont ORM, or Queries. I\'m not sure
In Laravel 5.5, I created a helper function for executing easier:
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());
}
}
For example:
$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);