duancong2160 2015-11-17 23:42
浏览 103
已采纳

如何使用Laravel Eloquent插入多个子项以及父记录

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:

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

Table schema:

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

Order Model (relationship):

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

OrderLine Model (relationship):

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

Store Function:

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


}
  • 写回答

1条回答 默认 最新

  • doucai1901 2015-11-17 23:51
    关注

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

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

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

    This, of course, is assuming Cart::content() is valid.

    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.

    Edit: 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog