2014-10-11 94 views
3

我有一個與Address模型有多態關係的Account模型。這被設置爲一到一個releationship設置像這樣:Laravel表單與一對一關係的綁定

帳戶:

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'); 
} 

在我的形式編輯的帳戶,我也有地址字段。我可以簡單地綁定我的賬戶對象:

{{ 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具有類似標題建議。這兩個我嘗試過,沒有舊的輸入。這是否只適用於多形關係或者我做錯了什麼?

另外,你如何處理控制器中的這些形式?

關係沒有任何關係在表單模型綁定文檔中,而搜索主要提出請求一對多綁定的人。

回答

6

它適用於任何* -to-一個關係(許多一對多,即模型的集合,它不會工作。):

// 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); 
+0

真棒。非常感謝。看起來我只是錯過了加載相關數據的部分。我沒有意識到這是你必須做的事情。 – Troncoso 2014-10-12 20:20:57