Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge collections in laravel from relations

Suppose I have 3 tables.

  1. Images
  2. Subject
  3. Style

The relationship is Many to Many(Images,Subject) and Many to Many(Images,Style). Now I want to do something like:

$result=$subjectResult->images()->merge($styleResult->images()). I want the type of result to be an Images Collection Object.

So far I've tried it as:

$subjectResult=Subject::with('images')->where(query)->get();

But this returns the subject rows,Image rows and the pivot rows. I want to extract the Images collection from it.

Image Model:

public function styles(){
    return $this->belongsToMany('Style','style_images','image_id','keyword_id');
}
public function subjects(){
    return $this->belongsToMany('Subject','subject_images','image_id','subject_id');
}

The ultimate objective is to get Image collection merged from results of query on subject and style.

like image 740
Abhishek Patel Avatar asked Feb 03 '26 19:02

Abhishek Patel


2 Answers

Image::has('styles')->orHas('subjects')->get();
like image 181
Chris Avatar answered Feb 05 '26 09:02

Chris


Okay, so here's what worked for me. Using whereHas and orWhereHas worked for me. Thanks for the help everyone.

$results=Image::whereHas('subjects',function($q) use ($searchParam){
            $q->where('subject','LIKE','%'.$searchParam.'%');
        })->orWhereHas('styles',function($q) use ($searchParam){
            $q->where('style','LIKE','%'.$searchParam.'%');
        })->get();
like image 41
Abhishek Patel Avatar answered Feb 05 '26 09:02

Abhishek Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!