2014-09-28 97 views
5

belongsToMany和屬於關聯關係合併的結果在我的Image模式,我有我的Article模型兩個關係,一個多到多,一個一個一對多:從雄辯

public function articlesAlbums() 
{ 
    return $this->belongsToMany('Article', 'article_image', 'image_id', 'article_id')->publishedFilter(); 
} 

public function articleThumb() 
{ 
    return $this->hasMany('Article')->publishedFilter(); 
} 

我合併結果從這些習慣的所有圖片由Article

public function getArticlesAllAttribute() 
{ 
    return $this->articlesAlbums->merge($this->articleThumb); 
} 

在我Article模型我有我的Image模型兩個關係:

public function images() 
{ 
    return $this->belongsToMany('Image', 'article_image', 'article_id', 'image_id'); 
} 

public function thumbnail() 
{ 
    return $this->belongsTo('Image', 'image_id'); 
} 

我想合併這些爲好,同樣我在Image模型做:

public function getImagesAllAttribute() 
{ 
    return $this->images->merge($this->thumbnail); 
} 

但是,這並不工作,這似乎是因爲我的縮略圖關係belongsTo,不hasMany 。所以也許它不是一個集合。當我嘗試,我得到一個例外:

Call to a member function getKey() on a non-object 

我已經試過它轉換爲一個集合:

new Collection($this->thumbnail) 

卻得到一個錯誤說:

__construct() must be of the type array, object given 

如何合併$this->images$this->thumbnail在我的Article模型中獲得的結果與我在Image模型中的結果相同?意思是結果合併爲無重複。

非常感謝。

更新:

由於剃刀讓我意識到,$this->thumbnail實際上沒有返回的集合,而是一個對象時,它讓我重新思考,如果merge真的要使用正確的函數。

return $this->images->merge($this->thumbnail()->get()); 

這似乎導致了很多不必要的查詢,即使我是渴望加載。

所以最後我做這個:

public function getImagesAllAttribute() 
{ 
    $imagesAll = $this->images; 
    if (! is_null($this->thumbnail)) $imagesAll->add($this->thumbnail); 

    return $imagesAll->unique(); 
} 

它大大減少查詢的數量,結果是一樣的。

+0

退房[這個問題](http://stackoverflow.com/questions/21615656/get-array-of -eloquent的模型 - 關係)。它可能會對你如何得出你的結果有所瞭解。你現在想做的事情不會奏效。 – 2014-10-01 20:26:15

回答

6

$this->thumbnail相同$this->thumbnail()->first(),得到一個集合,您可以嘗試:

public function getImagesAllAttribute() 
{ 
    return $this->images->merge($this->thumbnail()->get()); 
} 
+0

This Works!並且非常有意義(現在你指出了)。謝謝你:) – 2014-10-02 19:05:59

+0

歡迎你,很高興我能提供幫助。 – Razor 2014-10-02 21:37:20

+0

甚至不知道這個!謝謝! – Notflip 2017-01-09 10:53:50