Laravel 表单模型绑定与关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23448138/
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 Form Model Binding with Relationships
提问by Casey
Is it possible to bind a form with a model that has relationships? For example I have a Order model that has a one to many with a Details model. That would save a lot of time with
是否可以将表单与具有关系的模型绑定?例如,我有一个 Order 模型,它与一个 Details 模型具有一对多关系。这样可以节省很多时间
@foreach($order->details as $detail)
{{ Form::text('product_name', Input::old('product_name') ? Input::old('product_name') : detail->product_name)
@endforeach
回答by The Alpha
For a one-to-one
relation it's possible to use something like this:
对于one-to-one
关系,可以使用以下内容:
Form::text('detail[product_name]')
In this case $order->detail->product_name
will be populated in the given text box if an instance of Order
model is bound to the from
using Form::model($order)
with the related model Detail
but it may not possible for one-to-many
because simply there will be a collection and you need a loop.
在这种情况下$order->detail->product_name
,如果Order
模型的实例绑定到from
使用Form::model($order)
相关模型Detail
,则将在给定的文本框中填充,但可能无法实现,one-to-many
因为只有一个集合并且您需要一个循环。
回答by Aurel
To complete the answer of @WereWolf..
完成@WereWolf 的回答..
- Make an array of product_name
detail_names
- Input class allow you to access nested array by dot notation, eg:
orders.1.product_name
- Don't forget the second argument of
Input::old()
orInput::get()
is the default value, so you can specify the DB value and avoid conditional test..
- 制作一个 product_name 数组
detail_names
- 输入类允许您通过点符号访问嵌套数组,例如:
orders.1.product_name
- 不要忘记
Input::old()
or的第二个参数Input::get()
是默认值,这样你就可以指定 DB 值并避免条件测试..
.
.
Form::text('detail_names['.$detail->id.']', Input::old('detail_names.'.$detail->id, $detail->product_name))
In your controller, something like that:
在您的控制器中,类似的东西:
foreach(Input:get('detail_names') as $id => $product_name)
{
//...
}
Hope this will help you to save a bit of time.
希望这会帮助您节省一些时间。