Laravel save one to many relationship

╄→гoц情女王★ 提交于 2019-12-05 15:46:39

问题


I have the following relationships set up in Laravel:

OrderStatus Model
  - hasMany('Order')

 Order Model
  - 'belongsTo('OrderStatus');

The database is set up with an orders table and an order_statuses table. The orders table has a field for 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();

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?


回答1:


Sure you can do this:

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

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




回答2:


The correct way, to save a relationship for a new related model is as follows:

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

Documentation link : http://laravel.com/docs/4.2/eloquent#inserting-related-models



来源:https://stackoverflow.com/questions/27828476/laravel-save-one-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!