Php Laravel-雄辩ORM关系查询
我有5张桌子:Php Laravel-雄辩ORM关系查询,php,mysql,laravel,orm,eloquent,Php,Mysql,Laravel,Orm,Eloquent,我有5张桌子: 1. news 2. tags 3. filters 4. news_tag 5. tag_filters 表格结构如下: 新闻 id title description id title id title 标签 id title description id title id title 过滤器 id title description id title id title 新闻标签 id tag_id news_id 标记过滤器 id tag_i
1. news
2. tags
3. filters
4. news_tag
5. tag_filters
表格结构如下:
新闻
id
title
description
id
title
id
title
标签
id
title
description
id
title
id
title
过滤器
id
title
description
id
title
id
title
新闻标签
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', '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');代码>
当我将筛选id 1传递到我的路线时,我想检索与标记id 1相关的所有新闻。任何人都可以帮助我在控制器中执行此操作?没有简单的方法,但您可以使用以下方法:
News::select("news.*")
->join('tags'...)
->join('filters'...)
->where('filter_id',...)
->where('tag_id',...)
->get();
注意select()
说明。如果您跳过它,Laravel会将无效字段加载到您的News
模型中。当你加入雄辩的建设者时,这是必须的
如果您想在这种情况下快速加载关系,请使用查询生成器的with()
方法。您可以尝试一些嵌套的whereHas,而不是join。我对性能没有把握
$filterId = 1;
News::whereHas('tags', function($q1) use ($filterId) {
$q1->whereHas('filters', function($q2) use ($filterId) {
$q2->where('id', '=', $filterId);
});
});
你能为我详细说明一下加入的条件吗?问题是标签id与新闻id相关。因此,基本上我需要获取所有标签id,这些标签id与我传递到路线的过滤器id相关,然后查找所有与这些标签id相关的新闻id。