嵌套模型关系的形式 - Laravel

Gol*_*a11 5 php ruby-on-rails laravel laravel-4

在laravel中,是否有某种方式在表单中嵌套相关资源?

说我有这个:

class Person extends Eloquent {
  public function addresses() {
    return $this->hasMany("Address");
  }
}

class Address extends Eloquent {
  public function person() {
    return $this->belongsTo("Person");
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要一个Person表格来收集关于那个Person的信息Address.是否laravel促进这在某种程度上相当于Rails的accepts_nested_attributes_for :addressfields_for :address

我想要一些简单的东西,我可以在其中包含表格Address结果的字段Person,因为Address除了它之外并不存在Person.这有意义吗?

==编辑==

这是假设的代码

我正在寻找的东西是这样的:

{{ 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() }}
Run Code Online (Sandbox Code Playgroud)

Col*_*mes 13

您在输入名称的正确轨道上.

形成

// 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
Run Code Online (Sandbox Code Playgroud)

如果要添加地址,则需要生成一些随机密钥而不是地址ID.这将保持字段分组.

控制器逻辑

这是我处理输入的方式,使用'fillable'来过滤进入模型的数据.

// 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();
}
Run Code Online (Sandbox Code Playgroud)