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