在Laravel中创建一个Insert ... Select语句

时间:2014-08-27 17:34:57

标签: php mysql laravel

我需要将此查询转换为Laravel,并且我在尝试使用Laravel的Eloquont ORM或Queries创建Insert ... 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

6 个答案:

答案 0 :(得分:35)

没有办法在一个查询中执行此操作(除非您使用的是Laravel 5.7),但是我遇到了同样的问题,并希望确保我可以继续使用我使用QueryBuilder构建的某个选项。

所以你可以做些什么,把事情保持在清洁的一半,并重用之前构建了一个select语句的功能,是这样的:

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

更新Laravel 5.7

从Laravel 5.7.17起,您可以使用 - > insertUsing()。有关详细信息,请参阅here。谢谢@Soulriser指出这一点。

所以上面的查询看起来像这样:

DB::table('user_debt_collection')->insertUsing(['email','dinero'], $select);

答案 1 :(得分:10)

您可以使用:

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

首先,您需要为Demand创建一个模型,然后您可以使用:

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

然后,对于您的select语句,您可以执行与这些选项类似的操作:

$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';

手册herehere

中提供了更多信息

答案 4 :(得分:0)

尝试一下

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

答案 5 :(得分:0)

我使用了DB :: statement(...);

from turtle import Screen, Turtle

NUMBER_OF_SHAPES = 4
CURSOR_SIZE = 20

screen = Screen()

turtle = Turtle('triangle', visible=False)
turtle.fillcolor('white')
turtle.right(30)  # lay bottom on horizontal

for sizing in range(NUMBER_OF_SHAPES, 0, -1):

    turtle.shapesize(20 * sizing / CURSOR_SIZE)

    turtle.stamp()

screen.exitonclick()