我正在尝试使用order
保存order_items
但我在文档中找不到任何支持此用例的内容。一个hasMany关系。
基本上有一个orders
表格,其中包含id | user_id
和order_items
表格id | order_id | product_id
。
我如何save()
订单并同时使用一系列商品而无需循环遍历商品并单独保存?
这可能吗?
假设$items
的伪代码是一个数组:
$items = Session::get("cart.items");
$order = new Order;
$order->user_id = Auth::user()->id;
$order->order_items = $items;
$order->save();
答案 0 :(得分:9)
hasMany
关系所需的内容可以是saveMany
或createMany
,具体取决于$items
数组中的内容:
// array of attributes:
$items = [
['name'=>'item1','price'=>'price1'],
...
];
// then createMany:
$order->orderItems()->createMany($items);
这将在Item
表中创建新行。
// array of models:
$items = [
Item::find($someId),
Item::find($anotherId),
// and/or newly instantiated:
new Item(['name'=>'item1','price'=>'price1']),
...
];
// then createMany:
$order->orderItems()->saveMany($items);
这将关联(保存)现有模型,并创建不存在的模型。
另请注意,我使用camelCase关系名称orderItems
而不是order_items
。
这是一个重要的细节,因为Eloquent(Laravel v4)在处理关系(动态属性)时会在模型上查找camelCased方法。
//Order model
public function orderItems()
{
return $this->hasMany(...);
}
$order->orderItems; // collection
$order->order_items; // collection as well
// --------------------
// BUT
public function order_items()
{
return $this->hasMany(...);
}
$order->orderItems; // null
$order->order_items; // null
// the only way you can work with relation then, is explicitly use method like:
$order->order_items()->get();
答案 1 :(得分:1)
可能不是您正在寻找的最佳解决方案,但这应该有效。
假设该数组名为$items
,我的印象是您将其保存到数据透视表中。在下面的示例中,我在名为item_order
的{{1}}数据透视表上还有第3个字段。
item_quantity
基本上你将循环遍历foreach ($items as $item)
{
$order->items()
->attach($item['item_id'], ['item_quantity' => $item['item_quantity']]);
}
数组。这将假设您已在Order模型上定义了名为$items
的关系。
然后使用items()
方法
attach()
最后,如果您的数据透视表上没有第3个字段,则可以执行
->attach([insert the item_id], array('3rd field name' => 'value to be inserted')
您可以查看Laravel docs
中给出的示例注意强>
->attach($item_id)
是您只在数据库上创建记录时使用的方法,否则当您想要更新时需要不同的方法。
答案 2 :(得分:0)
请参考这个以及他的答案。
可填写或受保护的财产
创建新模型时,将属性数组传递给模型构造函数。然后通过质量分配将这些属性分配给模型。这很方便;然而,当盲目地将用户输入传递到模型中时,可能是严重的安全问题。如果用户输入被盲目地传递到模型中,则用户可以自由地修改模型的任何和所有属性。因此,默认情况下,所有Eloquent模型都可以防止质量分配。
因此,在模型上设置可填写或保护的属性。 Docs and Source
class User extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email');
}