gpt4 book ai didi

php - 在表单中嵌套模型关系 - Laravel

转载 作者:可可西里 更新时间:2023-11-01 13:39:00 25 4
gpt4 key购买 nike

在laravel中,有什么方法可以将相关资源嵌套在一个表单中吗?

假设我有这个:

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

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

我想要一个Person 表单来收集有关PersonAddress 的信息。 Laravel 是否以等同于 Rails 的 accepts_nested_attributes_for :addressfields_for :address 的方式促进了这一点?

我只是想要一些简单的东西,我可以在 Person 表单的结果中包含 Address 字段,因为 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() }}

最佳答案

您在正确的 rails 上输入了名称。

表单

// 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

如果您想添加地址,您需要生成一些随 secret 钥来代替地址 ID。这将使字段保持分组。

Controller 逻辑

这就是我处理输入的方式,使用“可填充”来过滤进入模型的数据。

// 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();
}

关于php - 在表单中嵌套模型关系 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20684932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com