2014-02-25 86 views
14

我試圖建立一個多態的一對一關係(has_one和belongs_to的多態等價物)。我有一個Address模型,還有其他幾個模型我想擁有一個地址。但是,我對文檔的措辭感到困惑。我已經看到了morphMany方法,但我的問題是:我應該使用morphMany,即使我只希望它有一個地址,或者是否有像我應該使用的morphOne方法?Laravel雄辯多態一對一?

編輯:我的Address模型具有這些領域,只是爲了幫助形象化:

Schema::create('addresses', function ($table) 
{ 
    $table->increments('id'); 
    $table->string('street'); 
    $table->string('street_more')->nullable(); 
    $table->string('city'); 
    $table->string('state')->nullable(); 
    $table->string('country'); 
    $table->string('postal_code'); 
    $table->integer('addressable_id'); 
    $table->string('addressable_type'); 
}); 
+0

這不是模型。這是遷移。 –

+0

@丹尼斯布拉加我指的是模型的結構。感謝您的支持!我已在帖子中澄清過。 – BenjaminRH

回答

20

是的,有一個morphOne方法,我認爲這是一個你應該在這種情況下使用:https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L811

您也可以使用

$table->morphs('addressable'); 

代替

$table->integer('addressable_id'); 
$table->string('addressable_type'); 

我用morphOne在自定義的包L4和工作得很好。

+3

太棒了!那只是沒有記錄。非常感謝你。 Re:'$ table-> morphs',我發現它更具可讀性,可以單獨將它們粘在那裏,但是謝謝:) – BenjaminRH

+2

感謝您的回答。我認爲這個函數現在叫做「morphOne」https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L792 –

1

試試這個,我認爲這比不支持的morphOne更好。

public function address() 
    { 
     return $this->hasOne('App\Address', 'addressable_id','id') 
        ->where('addressable_type', 'App\Model'); 
    }