php Laravel 保存一对多关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27828476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel save one to many relationship
提问by flyingL123
I have the following relationships set up in Laravel:
我在 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
.
数据库设置了一个orders
表和一个order_statuses
表。该orders
表有一个字段为order_status_id
。
When I save an Order, I manually set the order_status_id
by fetching the appropriate Order Status model, like this:
当我保存订单时,我order_status_id
通过获取适当的订单状态模型来手动设置,如下所示:
$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?
我想知道是否有内置函数来执行此操作而不是order_status_id
手动设置。我在 Laravel 文档中阅读了“附加相关模型”和“关联模型”,但我不知道这些是否适合我的用例。我认为我遇到的问题是我直接使用子模型(订单),并尝试设置它的父模型。有这个功能吗?
回答by lukasgeiter
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)
(status()
是belongsTo 关系。您可能需要调整该名称)
回答by Mysteryos
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
文档链接:http: //laravel.com/docs/4.2/eloquent#inserting-related-models