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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:32:54  来源:igfitidea点击:

Laravel save one to many relationship

phplaravellaravel-4eloquent

提问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 orderstable and an order_statusestable. The orderstable 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_idby 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_idmanually. 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