Reputation: 814
Suppose I have 3 tables.
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.
Upvotes: 3
Views: 1229
Reputation: 814
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();
Upvotes: 1
Reputation: 8673
You can get collection of images from subject and style separately and merge them into one single Collection Code is something like that
$images = new Collection();
$images = $images->merge($subject->images);
$images= $images->merge($style->images);
Upvotes: 0