web-dev-qa-db-fra.com

Créer une instruction Insert ... Select dans Laravel

J'ai besoin de convertir cette requête pour Laravel et je ne parviens pas à créer une instruction Insert ... Select avec Eloquont ORM de Laravel ou Queries. Je ne suis pas sûr de savoir comment procéder pour créer cette requête.

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

Comment est-il possible de créer cette requête en utilisant l'ORM de Laravel?

EDIT: Je ne suis pas sûr si cela est clair, mais je pense en termes de 1 requête, comme ils le font ici http://dev.mysql.com/doc/refman/5.0/en/insert-select .html

13
jamadri

Il n'y a aucun moyen de le faire dans une requête, mais je suis tombé sur le même problème et je voulais m'assurer de pouvoir continuer à utiliser un certain type de ma sélection avec le générateur de requêtes.

Donc, ce que vous pouvez faire, garder les choses à moitié ce qui est propre et réutiliser les fonctionnalités qui ont construit une instruction select auparavant, est la suivante:

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

Vous pouvez utiliser:

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]);
9
valmayaki

Dans Laravel 5.5, j'ai créé une fonction d'assistance pour exécuter plus facilement:

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

Par exemple:

$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);
1
NgocTP

Essaye ça

DB::table(table2)
    ->insert(
        (array) DB::table(table1)
            ->where('column', '=', $variable)
            ->select('column1','column2')
            ->first()
    );
0
Mark Kirshner Chico

Tout d’abord, vous devrez créer un modèle pour Demand. Vous pourrez alors utiliser:

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

Ensuite, pour votre instruction select, vous pouvez faire quelque chose de similaire à ces 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';

Il y a beaucoup plus d'informations dans le manuel ici et ici

0
Chris G