Create a Insert… Select statement in Laravel

前端 未结 6 1187
迷失自我
迷失自我 2020-12-11 14:41

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

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 15:18

    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);
    

提交回复
热议问题