从 eloquent 关系中获取数据 laravel
Get data from eloquent relationship with pivot in laravel
我有 3 个数据库 table。
显示
show_genres
show_show_genre
在我的表演模特中,我有:
public function genres()
{
return $this->belongsToMany('App\ShowGenre');
}
所以当我这样做时:
$show=Show::find(1);
$show->genres
给我在 shows_genres 数据库中具有 show_id 的所有流派的集合。
我也有 ShowGenre 模型,其中包含我拥有和使用的所有类型。
因为我想为我的流派使用同步,所以名称需要在数据库中。
但是我如何才能找到所有具有流派 ID 的节目。
我找不到任何方法来获取该列表。请帮忙,谢谢。
编辑:
你应该反过来做:
有流派模型
你在流派模型中的关系方法应该是
public function shows()
{
return $this->belongsToMany('App\Show', 'shows_genres');
}
belongsToMany 接受两个参数,模型和枢轴 table 名称(如果不是标准名称)。
您的解决方案:
//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;
}
读取多对多关系:
https://laravel.com/docs/6.x/eloquent-relationships#many-to-many
您可以使用
$show->genres()
->wherePivot('column', value)
->get();
By default Pivot table name must be singular : show_genre (without
plural s)
见docs
假设您的流派模型中存在这种关系
public function shows()
{
return $this->belongsToMany('App\Show', 'shows_genres', 'genre_id', 'show_id');
}
然后就可以像这样直接通过流派id获取所有节目
$shows = Genre::find($id)->shows;
我有 3 个数据库 table。
显示
show_genres
show_show_genre
在我的表演模特中,我有:
public function genres()
{
return $this->belongsToMany('App\ShowGenre');
}
所以当我这样做时:
$show=Show::find(1);
$show->genres
给我在 shows_genres 数据库中具有 show_id 的所有流派的集合。
我也有 ShowGenre 模型,其中包含我拥有和使用的所有类型。
因为我想为我的流派使用同步,所以名称需要在数据库中。
但是我如何才能找到所有具有流派 ID 的节目。
我找不到任何方法来获取该列表。请帮忙,谢谢。
编辑:
你应该反过来做:
有流派模型
你在流派模型中的关系方法应该是
public function shows()
{
return $this->belongsToMany('App\Show', 'shows_genres');
}
belongsToMany 接受两个参数,模型和枢轴 table 名称(如果不是标准名称)。
您的解决方案:
//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;
}
读取多对多关系:
https://laravel.com/docs/6.x/eloquent-relationships#many-to-many
您可以使用
$show->genres()
->wherePivot('column', value)
->get();
By default Pivot table name must be singular : show_genre (without plural s)
见docs
假设您的流派模型中存在这种关系
public function shows()
{
return $this->belongsToMany('App\Show', 'shows_genres', 'genre_id', 'show_id');
}
然后就可以像这样直接通过流派id获取所有节目
$shows = Genre::find($id)->shows;