问题描述
在laravel中,有什么方法可以将相关资源嵌套在表单中?
In laravel, is there some way of nesting related resources in a form?
说我有这个:
class Person extends Eloquent {
public function addresses() {
return $this->hasMany("Address");
}
}
class Address extends Eloquent {
public function person() {
return $this->belongsTo("Person");
}
}
,并且我想要一个Person
表单来收集有关该Person
的Address
es的信息. laravel是否以与Rails的accepts_nested_attributes_for :address
和fields_for :address
等效的方式来实现这一目的?
and I want a Person
form to collect information about that Person
's Address
es. Does laravel facilitate this in a way that is equivalent to Rails' accepts_nested_attributes_for :address
and fields_for :address
?
我只想简单地将Address
字段包含在Person
表单的结果中,因为除了Person
之外,Address
并没有真正存在.这有道理吗?
I'd just like something simple where I can include the Address
fields with the results of the Person
form, since the Address
doesn't really exist apart from the Person
. Does this make sense?
==编辑==
这是假设代码
我正在寻找的东西与此类似:
What I'm looking for is something that would resemble this:
{{ Form::model(new Person, array("action" => "admin\PersonController@store", "method" => "POST")) }}
{{ Form::text("name", array(...)) // <input name='person[name]' ... /> }}
{{ Form::email("email", array(...)) // <input name='person[email]' ... /> }}
{{ Form::fields_for("addresses"/* Would be name of relation */) }}
{{ Form::text("street_address") // <input name='person[addresses][][street_address]' ... /> }}
{{ Form::close_fields() }}
{{ Form::close() }}
推荐答案
您在正确的位置上输入了名称.
You are on the right track with the input names.
表格
// Form open, Person fields, etc...
<h2>Addresses</h2>
@foreach ($addresses as $address)
<fieldset>
{{ Input::text('addresses['.$address->id.'][address_1]', $address->address_1) }}
{{ Input::text('addresses['.$address->id.'][address_1]', $address->address_2) }}
{{ Input::text('addresses['.$address->id.'][city]', $address->city) }}
{{ Input::text('addresses['.$address->id.'][state]', $address->state) }}
{{ Input::text('addresses['.$address->id.'][zip]', $address->zip) }}
</fieldset>
@endforeach
// Form Close
如果要添加地址,则需要生成一些随机密钥来代替地址ID.这样会将字段分组.
If you want to add addresses you'll need to generate some random key to use instead of the address id. This will keep the fields grouped.
控制器逻辑
这就是我处理输入的方式,使用可填充"过滤进入模型的数据.
This is how I would handle input, using 'fillable' to filter the data going into the models.
// Get the Person model, fill, save, etc...
$addressIds = array();
foreach (Input::get('addresses', array()) as $id => $addressData)
{
$address = Address::find($id) ?: new Address;
$address->fill($addressData);
$address->save();
$addressIds[] = $address->id;
}
$changes = $person->addresses()->sync($addressIds);
// Delete the unused addresses
foreach ($changes['detached'] as $detachedAddressId)
{
$address = Address::find($detachedAddressId);
if (!empty($address)) $address->delete();
}
这篇关于表格中的嵌套模型关系-Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!