从关系合并收藏品 [英] Merge collections in laravel from relations

查看:141
本文介绍了从关系合并收藏品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有3个表。


  1. 图片

  2. 主题

  3. 样式

关系是多对多(图像,主题)和多对多(图像,样式)。
现在我想做一些例子:



$ result = $ subjectResult-> images() - > merge styleResult->图像())
我希望结果的类型成为一个Images Collection对象。



到目前为止,我已经尝试过:

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

但是这返回主题行,图像行和枢轴列。我想从中提取图像集合。



图像模型:

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

最终目标是从查询结果中获取图像集合关于主题和风格。

解决方案

好的,所以这里对我有用。使用 whereHas 或WhereHas 为我工作。感谢大家的帮助。

  $ results = Image :: whereHas('subjects',function($ q)use searchParam){
$ q-> where('subject','LIKE','%'。$ searchParam。'%');
}) - > orWhereHas('styles' ($ q)use($ searchParam){
$ q-> where('style','LIKE','%'。$ searchParam。'%');
}) - >得到();


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.

解决方案

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

这篇关于从关系合并收藏品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆