我正在尝试使用 Laravel 创建一个简单的购物应用程序,我正在使用 LaravelShoppingCart用于在用户 session 中存储项目的插件。当用户点击我的 store
方法时,应存储 order
和 order_line
记录。
我目前收到此错误,代码如下:
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 模型,如下所示:
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
集合即可;
$order->order_line()->saveMany($order_lines);
当然,这是假设 Cart::content()
有效。
相关说明:saveMany
不会通过单个查询插入所有条目。它将循环并一一添加它们。要仅使用单个查询进行批量插入,您需要使用查询生成器。
编辑:如何使用 insert
的示例使用查询生成器的方法:
$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);
您只需构建一个要插入表中的数据数组并将其插入。
关于php - 如何使用 Laravel Eloquent 插入多个子记录和父记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33769216/