我有5个表:
1. news
2. tags
3. filters
4. news_tag
5. tag_filters
表格结构如下:
新闻
id
title
description
标签
id
title
过滤器
id
title
news_tag
id
tag_id
news_id
标签过滤器
id
tag_id
filter_id
举个例子,我的表有以下记录:
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
我的模型中的关系如下:
新闻模型
public function tags(){
return $this->belongsToMany('App'Tag', 'news_tag');
}
标签型号
public function news(){
return $this->belongsToMany('App'News', 'news_tag');
}
public function filters(){
return $this->belongsToMany('App'Filter', 'tag_filter');
}
过滤器模型
public function tags(){
return $this->belongsToMany('App'Tag', 'tag_filter');
}
假设我的路线如下:Route::get('news/filter/{filter_id}','NewsController@getNews');
当我将filter_id1传递到我的路由时,我想检索与tag_id1
没有简单的方法可以做到这一点,但你可以使用这样的东西:
News::select("news.*")
->join('tags'...)
->join('filters'...)
->where('filter_id',...)
->where('tag_id',...)
->get();
注意select()
指令。如果跳过它,Laravel将把无效字段加载到News
模型中。当你加入Eloquent Builder时,它是必备的。
如果您想在这种情况下急切地加载关系,请使用查询生成器的with()
方法。
您可以尝试一些嵌套的whereHas而不是join。我对表现不太确定。
$filterId = 1;
News::whereHas('tags', function($q1) use ($filterId) {
$q1->whereHas('filters', function($q2) use ($filterId) {
$q2->where('id', '=', $filterId);
});
});