从关系合并收藏品 [英] Merge collections in laravel from relations
问题描述
- 图片
- 主题
- 样式
关系是多对多(图像,主题)和多对多(图像,样式)。
现在我想做一些例子:
$ 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.
- Images
- Subject
- 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屋!