2016-12-05 187 views
0

早上好,我在Eloquent的模型關係上遇到了一些麻煩,我需要鏈接那些具有中間表的文章和圖像。在中間表中,我想添加文章和圖片的ID,並且我想檢索屬於文章的所有圖片,管理關係的最佳方式是什麼?在此先感謝laravel雄辯中的一對多關係

+1

https://laravel.com/docs/5.3/eloquent-relationships#one-to-many Laravel有很好的文檔記錄,如果你閱讀文檔,你不需要問這個問題。 – Devon

回答

0

您可以使用morphMany()關係(Polymorphic Relationship),以解決您的問題是這樣的:

UPDATE:表結構如下所示:

- articles 
    - id 
    - title 
    - content 
    - ... 

- images 
    - id 
    - owner_id 
    - owner_type (Here there can be - Article, Auction, User, etc) 
    - name 
    - mime_type 
    - ... 

多態性關係允許模型屬於多於一個 其他模型上的單個關聯。例如,想象一下 您的應用程序的用戶可以對帖子和視頻進行「評論」。使用 多態關係,可以爲這兩種情況都使用單個註釋表 。

你的車型將是這樣的:

class Article extends Model 
{ 

    public function images() 
    { 
     return $this->morphMany(Image::class, 'owner'); 
    } 

} 

class Image extends Model 
{ 

    public function owner() 
    { 
     return $this->morphTo(); 
    } 

} 

多個圖像保存到一個文章,你可以這樣做:

$article->images()->create([... inputs_arr ...]); 

,並獲取它們,你可以做到這一點像:

$articleImages = Article::find($id)->images; 

希望這有助於!

+0

那麼,它如何保存表格上的數據?它在哪裏使數據庫的關係?我在創建模型之前創建了數據庫,因爲我以前正在使用純PHP。感謝:D –

+0

這個案件將會有兩張表格。你的表格結構就像我上面更新的答案中所示。 –

+0

如果我使用與其他模型相關的圖像表,比如說拍賣,用戶等,不會有問題嗎? –

3

您不需要使用數據透視表,因爲它是one-to-many的關係。

只需使用hasMany()關係:

public function images() 
{ 
    return $this->hasMany('App\Image'); 
} 

然後用eager loading加載所有圖片與文章:

$article = Article::with('images')->where('id', $articleId)->first();