私の Image
モデル私は私と2つの関係を持っています Article
モデル、1対多および1対多:
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
モデル私は私と2つの関係を持っています 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();
}
クエリの数が大幅に減り、結果は同じです。
回答:
回答№1は6$this->thumbnail
〜と同じです $this->thumbnail()->first()
、コレクションを取得するには、次のことを試してください。
public function getImagesAllAttribute()
{
return $this->images->merge($this->thumbnail()->get());
}