首先,文檔里面講述的不是特別詳細,詳細尋找查詢流程沒有過多介紹,只是介紹如何去定義,直接使用,導致很多該明白的東西,沒有說明,下面詳細看看這個多態關聯
是怎么定義,使用,詳細查詢的。
先看文檔介紹
多態關聯允許一個模型在單個關聯下屬於多個不同模型。例如,假如你想要為產品和職工存儲照片,使用多態關聯,你可以在這兩種場景下使用單個photos
表,首先,讓我們看看構建這種關聯關系需要的表結構:
staff id - integer name - string products id - integer price - integer photos id - integer path - string imageable_id - integer imageable_type - string
兩個重要的列需要注意的是photos
表上的imageable_id
和imageable_type
。imageable_id
列包含staff
或product
的ID值,而imageable_type
列包含所屬模型的類名。當訪問imageable
關聯時,ORM根據imageable_type
列來判斷所屬模型的類型並返回相應模型實例。
如何定義:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Photo extends Model{ /** * 獲取所有擁有的imageable模型 */ public function imageable() { return $this->morphTo(); } } class Staff extends Model{ /** * 獲取所有職員照片 */ public function photos() { return $this->morphMany('App\Photo', 'imageable'); } } class Product extends Model{ /** * 獲取所有產品照片 */ public function photos() { return $this->morphMany('App\Photo', 'imageable'); } }
在每個模型中 都這樣定義一下,定義morpto方法的都是這個模型中,字段是帶有imageable_id
和imageable_type的。id就是其他關聯到這個模型的id,type就是哪一個類,里面數據庫怎么填呢,id,填3,imageable_type填 app\Product 就表示,這個圖片是和產品表里面的id為3的那條數據關聯,注意了!,這里后面type字段,類一定要加app\類,加app方可,不然這個類是找不到的,他是根據laravel的類機制來運行的。
那么現在怎么使用呢:
$product = App\Product::find(3); dd($product->photos);
這句話的意思就是,找產品表里id為3的那條數據,在到photo表里找imageable_id
和imageable_type的值是什么,如果值為3和app\Product的數據,表明關聯關系OK,否則就找不到
反其道而行之,可以直接使用主關聯的模型,就是所謂的morphTo
方法,這個是主關聯,因為他直接關聯2個表,就可以查看,這個模型,所擁有的產品和職員是哪些了。
$photo = App\Photo::find(3); $imageable = $photo->imageable;
這個意思是,查看photo表里id為3的那條數據,看他的imageable_id
和imageable_type是什么,如果是1和app\Product的話,就會去Product表里去找id為1的數據,然后顯示出來了。沒有數據就為空。如果是2和app\Staff的話,就回去Staff表里找id為2的數據,有則顯示。