Merge collections in laravel from relations

亡梦爱人 提交于 2019-12-13 15:13:59

问题


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.


回答1:


Image::has('styles')->orHas('subjects')->get();



回答2:


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);



回答3:


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();


来源:https://stackoverflow.com/questions/29666726/merge-collections-in-laravel-from-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!