2017-10-19 117 views
0

我有一個變形關係,主體可以有多個關係。它們的存在取決於變形的模型。我需要檢索所有相關模型(whereHas()不能解決問題),並且如果它們存在於特定模型上(with()將不起作用,因爲關係不總是存在),我希望它們的關係被加載。只有在關係存在的情況下才進行加載

還有什麼其他內置的東西可以用來流暢地解決這種情況,或者黑客是唯一的解決方法嗎?

<?php 

... 

class Post extends Model 
{ 
    /** 
    * Get all of the post's comments. 
    */ 
    public function comments() 
    { 
     return $this->morphMany('App\Comment', 'commentable'); 
    } 

    /** 
    * This relationship is available for Post model only 
    */ 
    public function relationA() 
    { 
     // return $this->hasMany(...); 
    } 
} 

class Video extends Model 
{ 
    /** 
    * Get all of the video's comments. 
    */ 
    public function comments() 
    { 
     return $this->morphMany('App\Comment', 'commentable'); 
    } 

    /** 
    * This relationship is available for Video model only 
    */ 
    public function relationB() 
    { 
     // return $this->hasMany(...); 
    } 
} 

class Comment extends Model 
{ 
    /** 
    * Get all of the owning commentable models. 
    */ 
    public function commentable() 
    { 
     return $this->morphTo(); 
    } 

    public static function feed() 
    { 
     self::with('commentable') 
      ->withIfExists(['commentable.relationA', 'commentable.relationB']) 
      // ... 
      ->get(); 
    } 

    public function scopeWithIfExists($query, $relation) 
    { 
     // There is no way to implement such a scope 
     // in order to reduce umber of queries by eager loading relations 
     // as we don't know of what type the subject is 
     // without looking it up in database 
    } 
} 

回答

0

退房Query Scopes

隨着可以創建一個範圍,如果它存在加載關係,例如:

User::withRelationIfExists('cars')->where(...) 

例如:(代碼未測試)

public function scopeWithRelationIfExists($query, $relation) 
{ 
    if (! method_exists(get_class(), $relation)) { 
     return; 
    } 

    return $query->with($relation); 
} 
+0

這種方法不能解決問題我的想法是。它要麼加載它或不加載,但對於所有人。所以你要麼在當前模型上定義關係,laravel會急於加載或不加載,並且不會加載任何。或者我錯過了什麼? – notnull

+0

此方法是一種自定義幫助程序,可輕鬆加載關係,而無需一直檢查。如果你想使用它,你需要在Model中聲明該方法,或者創建一個Parent模型來繼承,或者將它添加到Trait中,並在你想要這個自定義範圍的模型中使用它。如果您不知道關係的名稱,則無法告訴Laravel自動加載關係。 – Lloople

+0

我理解範圍,我開始按照你的建議實現它,但是有一點我意識到它沒有意義,因爲如果你有morphMany關係,對象的類將被存儲在數據庫中(因爲有可能是各種類型的,正確的),所以你不能檢查是否有這樣的關係之前,你查詢分貝,這是它的所有破壞。 – notnull

相關問題