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();
}
它大大減少查詢的數量,結果是一樣的。
退房[這個問題](http://stackoverflow.com/questions/21615656/get-array-of -eloquent的模型 - 關係)。它可能會對你如何得出你的結果有所瞭解。你現在想做的事情不會奏效。 – 2014-10-01 20:26:15