Combining results from ownToMany and relates to relationships in Eloquent

In my Image model, I have two connections to my Article model, one of many to many and one one to many:

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

I will combine the results from them to get all the images used by Article :

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

In my Article model, I have two connections to my Image model:

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

I would also like to combine them the same way as in my Image model:

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

But this does not work, it seems, because my reduced relation belongsTo , not hasMany . So maybe this is not a collection. When I try to get an exception:

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

I tried converting it to a collection with:

 new Collection($this->thumbnail) 

but get an error message:

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

How can I combine $this->images and $this->thumbnail in my Article model to get the same results as my Image model? This means that the results are combined without duplicates.

Many thanks.

Update:

Since Razor made me realize that $this->thumbnail does not actually return a collection, but rather a single object, it made me rethink if merge really a suitable function.

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

It seemed to cause a ton of unnecessary requests, even though I wanted to download.

So, I did this instead:

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

This drastically reduced the number of queries, and the result remained the same.

+5
source share
1 answer

$this->thumbnail same as $this->thumbnail()->first() , to get the collection you can try:

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

Source: https://habr.com/ru/post/1203569/


All Articles