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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题