我有一个 Account 模型,它与 Address 模型具有多态关系。这是设置为一对一的关系,如下所示:
账号:
public function address()
{
return $this->morphOne('Address', 'hasAddress', 'add_hasaddress_type', 'add_hasaddress_id', 'act_id');
}
地址:
public function hasAddress()
{
return $this->morphTo('hasAddress', 'add_hasaddress_type', 'add_hasaddress_id');
}
在我用于编辑帐户的表单上,我还有地址字段。我可以通过以下方式简单地绑定(bind)我的帐户对象:
{{ Form::model($account, array('route' => array('accounts/edit', $account->act_id), 'method' => 'put')) }}
{{ Form::label('act_name', 'Account Name:') }}
{{ Form::text('act_name', Input::old('act_name')) }}
然后正确填写字段。但是,如何填充地址字段?根据我的研究,我需要做的是:
{{ Form::text('address.add_city', Input::old('address.add_city')) }}
访问关系的值,但这不起作用。
我也试过
{{ Form::text('address[add_city]', Input::old('address[add_city]')) }}
正如具有类似标题的 SO 所建议的那样。这两个我都尝试过使用和不使用旧输入。这是否不适用于多态关系,还是我做错了什么?
另外,在 Controller 中如何处理这些表单?
在表单模型绑定(bind)文档中没有关于关系的内容,搜索主要是提出一对多绑定(bind)的要求。
最佳答案
它适用于任何 * 对一关系(对于多对多,即它不会工作的模型集合):
// prepare model with related data - eager loading
$account = Account::with('address')->find($someId);
// or lazy loading
$account = Account::find($someId);
$account->load('address');
// view template
{{ Form::model($account, ...) }}
Account: {{ Form::text('acc_name') }}
City: {{ Form::text('address[add_city]') }}
{{ Form::close() }}
不需要 Input::old
或任何东西,null
作为默认值就足够了。 Laravel 将按以下顺序填充数据(Docs are wrong here!):
1. old input
2. bound data
3. value passed to the helper
请注意,您必须加载关系(动态调用在这种情况下不起作用)。
另一件事是稍后处理输入 - Laravel 不会自动混合相关模型,所以你需要这样的东西:
$accountData = Input::only(['acc_name', ... other account fields]);
// or
$accountData = Input::except(['address']);
// validate etc, then:
$account->fill($accountData);
$addressData = Input::get('address');
// validate ofc, then:
$account->address->fill($addressData);
关于php - 具有一对一关系的 Laravel 表单绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319956/