[英]Laravel - Eloquent ORM Relationship Query
I have 5 tables: 我有5张桌子:
1. news
2. tags
3. filters
4. news_tag
5. tag_filters
The tables structure are as follows: 表格结构如下:
news 新闻
id
title
description
tags 标签
id
title
filters 过滤器
id
title
news_tag news_tag
id
tag_id
news_id
tag_filter TAG_FILTER
id
tag_id
filter_id
Let's say for example my tables have the following records: 比方说我的表有以下记录:
news: id = 1 title = News_1 Description = Details for News_1
tags: id = 1 title = PHP
filters: id = 1 title = PHP News
news_tag: id = 1 tag_id = 1 news_id = 1
tag_filter: id = 1 tag_id = 1 filter_id = 1
The relationships in my models are as follows: 我模型中的关系如下:
News model 新闻模式
public function tags(){
return $this->belongsToMany('App\Tag', 'news_tag');
}
Tag model 标签模型
public function news(){
return $this->belongsToMany('App\News', 'news_tag');
}
public function filters(){
return $this->belongsToMany('App\Filter', 'tag_filter');
}
Filter model 过滤模型
public function tags(){
return $this->belongsToMany('App\Tag', 'tag_filter');
}
Let's say my route is as follows: Route::get('news/filter/{filter_id}','NewsController@getNews');
假设我的路线如下: Route::get('news/filter/{filter_id}','NewsController@getNews');
I want to retrieve all the news related to tag_id 1 when I pass filter_id 1 to my route. 当我将filter_id 1传递给我的路线时,我想要检索与tag_id 1相关的所有新闻。 Anyone can help me how to do this in my controller? 任何人都可以帮助我如何在我的控制器中执行此操作?
There is no simple way to do this, but you can use something like this: 没有简单的方法可以做到这一点,但你可以使用这样的东西:
News::select("news.*")
->join('tags'...)
->join('filters'...)
->where('filter_id',...)
->where('tag_id',...)
->get();
Note select()
instruction. 注意select()
指令。 If you skip it, Laravel will load invalid fields into your News
models. 如果您跳过它,Laravel会将无效字段加载到您的News
模型中。 It's must-have when you do joins in Eloquent Builder. 当您加入Eloquent Builder时必须拥有它。
If you want to eager load relations in this case, use with()
method of the query builder. 如果您想在这种情况下急切加载关系,请使用查询构建器的with()
方法。
You can try some nested whereHas instead of join. 您可以尝试一些嵌套的whereHas而不是join。 I'm not sure about performance. 我不确定性能。
$filterId = 1;
News::whereHas('tags', function($q1) use ($filterId) {
$q1->whereHas('filters', function($q2) use ($filterId) {
$q2->where('id', '=', $filterId);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.