我如何使用Laravel Eloquent插入多个子项以及父记录 [英] How can I insert multiple children along with parent record using Laravel Eloquent

查看:30
本文介绍了我如何使用Laravel Eloquent插入多个子项以及父记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Laravel创建一个简单的购物应用程序,我正在使用 LaravelShoppingCart 用于在用户会话中存储项目的插件.当用户点击我的 store 方法时,应该存储 order order_line 记录.

I am trying to create a simple shopping application using Laravel, I am using LaravelShoppingCart plugin to store items in the user session. When the user hits my store method the order and order_line records should be stored.

我目前通过以下代码收到此错误:

I am currently getting this error with the code below:

参数1传递给Illuminate \ Database \ Eloquent \ Model :: __ construct()必须是数组类型,给定对象,在/home/vagrant/site/app/Http/Controllers/BasketController.php在线130,并且已定义

Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given, called in /home/vagrant/site/app/Http/Controllers/BasketController.php on line 130 and defined

表架构:

// create orders table
Schema::create('orders', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users');
    $table->text('order_notes')->nullable();
    $table->decimal('subtotal', 5, 2)->default(0);
    $table->timestamps();
});

// create order lines table
Schema::create('order_lines', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('order_id')->unsigned();
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
    $table->integer('menu_item_id')->unsigned();
        $table->foreign('menu_item_id')->references('id')->on('menu_item');
    $table->decimal('sale_price', 5, 2);
    $table->integer('quantity');
    $table->timestamps();
});

订单模型(关系):

/**
 * Define relationship to OrderLines
 * @return [type] [description]
 */
public function order_line()
{
    return $this->hasMany('App\OrderLine');
}

订单行模型(关系):

public function order()
{
    return $this->belongsTo('App\Order');
}

存储功能:

public function store(CreateOrderGuestRequest $request)
{

    $order = new Order;

    $order->order_notes = $request->order_notes;
    $order->save();

    $order_lines = new Collection();

    foreach (Cart::content() as $row) {
        $order_lines->push([
            'menu_item_id' => $row->id,
            'quanity'      => $row->qty,
            'sale_price'   => $row->price
        ]);
    }

    $order->order_line()->saveMany(new OrderLine($order_lines));

    // redirect somewhere after


}

推荐答案

您非常接近.您只需要进行一些调整即可使其生效.您需要将模型集合或模型数组传递给 saveMany 方法,这样当您遍历循环时,而不是推送"一个数组,而是推送"一个新的OrderLine模型,如下所示:

You were pretty close. You just need to make a few adjustments to get this to work. You need to pass a collection of models or an array of models to the saveMany method so when you loop through, instead of "pushing" an array, "push" a new OrderLine model like this:

foreach (Cart::content() as $row) {
    $order_lines->push(
        new OrderLine([
            'menu_item_id' => $row->id,
            'quanity'      => $row->qty,
            'sale_price'   => $row->price
        ])
    );
}

然后,当您调用 saveMany 时,只需传递 $ order_lines 集合;

Then, when you call saveMany, just pass the $order_lines collection;

$order->order_line()->saveMany($order_lines);

这当然是假设 Cart :: content()有效.

有关说明: saveMany 不会在单个查询中插入所有条目.它将循环遍历并一一添加.要仅使用单个查询进行批量插入,您需要使用查询生成器.

On a related note: saveMany will not insert all the entries with a single query. It'll loop through and add them one-by-one. To do a bulk insert with just a single query, you need to use the query builder.

如何使用 插入 使用查询构建器的方法:

An example of how to use the insert method using the query builder:

$order_lines = [];

foreach (Cart::content() as $row) {
    $order_lines[] = [
        'menu_item_id' => $row->id,
        'quanity'      => $row->qty,
        'sale_price'   => $row->price,
        'order_id'     => $order->id
    ];
}

DB::table('order_lines')->insert($order_lines);

您只需构建一个数据数组即可插入表中并将其插入.

You just build an array of data to insert into the table and insert it.

这篇关于我如何使用Laravel Eloquent插入多个子项以及父记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆