laravel - 使用 laravel 中的枢轴从 eloquent 关系中获取数据
问题描述
我有 3 个数据库表。
节目
show_genres
show_show_genre
在我的展示模型中,我有:
public function genres()
{
return $this->belongsToMany('App\ShowGenre');
}
所以当我这样做时:
$show=Show::find(1);
$show->genres
给我所有在 show_genres db 中有 show_id 的流派的集合。
我也有 ShowGenre 模型,我拥有和使用的所有流派都在哪里。
因为我想对我的流派使用同步,所以名称需要在数据库中。
但是我怎样才能找到所有具有流派 ID 的节目。
我找不到任何方法来获取该列表。请帮忙,谢谢。
编辑:
解决方案
You should do this other way around:
Have a model for Genre
your relationship method in Genre model should be
public function shows()
{
return $this->belongsToMany('App\Show', 'shows_genres');
}
belongsToMany accepts two parameters, model and pivot table name if not a standard name.
Your solution:
//Get genre 'strict'
//where could be followed by column name example:whereSlug, whereName
$strictGenre = Genre::whereName('strict')->first();
if($strictGenre)
{
//get shows of this genre
$strictShows = $strictGenre->shows;
}
Read manytomany relationships:
https://laravel.com/docs/6.x/eloquent-relationships#many-to-many
推荐阅读
- javascript - webpack 块名称动态导入的公共路径问题
- javascript - 使用钩子获取数据需要很长时间
- swift - 有没有办法在 UITest 中使用 .selectedSegmentIndex 而不是 .buttons["name"]?
- expect - 期望脚本以交互方式回答问题
- javascript - 反应,axios,内容类型
- apache-kafka - Kafka - 未压缩主题与压缩主题
- java - 使用 Java API for Bitbucket 在空存储库中创建分支
- azure-devops-server-2019 - 如何根据天在 azure devops 2019 中指定不同的 sprint 容量?
- javascript - 排除特定 URL 的 React-router 动态 URL
- excel - 找不到使用的外部参考缺失的位置