简体   繁体   English

从关系中合并laravel中的集合

[英]Merge collections in laravel from relations

Suppose I have 3 tables. 假设我有3个表。

  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()) . $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. 我想从中提取Images集合。

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. 最终目标是从主题和样式的查询结果中合并Image集合。

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

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

Okay, so here's what worked for me. 好的,这就是对我有用的东西。 Using whereHas and orWhereHas worked for me. 使用whereHasorWhereHas为我工作。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM