Create a Insert… Select statement in Laravel

前端 未结 6 1050
迷失自我
迷失自我 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:14

    Try this

    DB::table(table2)
        ->insert(
            (array) DB::table(table1)
                ->where('column', '=', $variable)
                ->select('column1','column2')
                ->first()
        );
    
    0 讨论(0)
  • 2020-12-11 15:15

    I used DB::statement(...);

    BD::statement(INSERT INTO table (SELECT));
    
    0 讨论(0)
  • 2020-12-11 15:17

    First, you'll need to create a model for Demand, so then you can use:

    $demand = new Demand;
    $demand->Login = $login;
    $demand->Name = $name;
    [...]
    $demand->save(); // <~ this is your "insert" statement
    $id = $demand->id;
    

    Then for your select statement you can do something similar to these options:

    $demand = Demand::find($id); // will be similar to: SELECT * FROM Demand WHERE `id` = '$id';
    $demand = Demand::where('id', $id)->get(); //same as above
    $demand = Demand::where('id', $id)->get(array('Login', 'Name')); // will be similar to: SELECT `Login`, `Name` FROM Demand WHERE `id` = '$id';
    

    There is a lot more information in the manual here and here

    0 讨论(0)
  • 2020-12-11 15:18

    There is no way of doing this in one query (unless you are on Laravel 5.7), however I came across the same issue and wanted to make sure I can keep using a certain select I build with the QueryBuilder.

    So what you could do, to keep things half what clean and to reuse functionality which has built a select statement before, is this:

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

    UPDATE Laravel 5.7

    As of Laravel 5.7.17 you can use ->insertUsing(). See here for details. Thank you @Soulriser for pointing this out.

    So above query would look like this:

    DB::table('user_debt_collection')->insertUsing(['email','dinero'], $select);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-11 15:20

    You can use:

    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]);
    
    0 讨论(0)
提交回复
热议问题