Laravel保存一对多关系

问题描述:

我在Laravel中建立了以下关系:

I have the following relationships set up in Laravel:

OrderStatus Model
  - hasMany('Order')

 Order Model
  - 'belongsTo('OrderStatus');

使用orders表和order_statuses表建立数据库. orders表具有用于order_status_id的字段.

The database is set up with an orders table and an order_statuses table. The orders table has a field for order_status_id.

保存订单时,通过获取适当的订单状态"模型来手动设置order_status_id,如下所示:

When I save an Order, I manually set the order_status_id by fetching the appropriate Order Status model, like this:

$status = OrderStatus::where(['name'=>'sample_status'])->firstOrFail();
$order->order_status_id = $status->id;
$order->save();

我想知道是否有内置函数来执行此操作,而不是手动设置order_status_id.我已经在Laravel文档中阅读了有关附加相关模型"和关联模型"的信息,但是我无法弄清楚它们是否适合我的用例.我认为我遇到的问题是我正在直接使用子模型(订单),并尝试将其设置为父模型.有功能吗?

I'm wondering if there is a built in function to do this rather than setting the order_status_id manually. I've read about "Attaching a related model", and "Associating Models" in the Laravel docs, but I can't figure out if these fit my use case. I think the issue I'm having is that I'm working directly with the child model (the order), and trying to set it's parent. Is there a function for this?

您可以执行以下操作:

$status = OrderStatus::where(['name'=>'sample_status'])->firstOrFail();
$order = new Order;
$order->status()->associate($status);
$order->save();

(status()是belongsTo关系.您可能需要调整该名称)

(status() is the belongsTo relation. You might need to adjust that name)