繁体   English   中英

从与laravel中的枢轴的雄辩关系中获取数据

[英]Get data from eloquent relationship with pivot in laravel

我有 3 个 DB 表。

显示

我的节目表

节目类型

表与我的流派

show_show_genre

在此处输入图片说明

在我的表演模型中,我有:

public function genres()
    {
        return $this->belongsToMany('App\ShowGenre');
    }

所以当我这样做时:

$show=Show::find(1);

$show->genres为我提供了所有在 show_genres db 中具有 show_id 的流派的集合。

我还有 ShowGenre 模型,其中包含我拥有和使用的所有类型。

因为我想对我的流派使用同步,所以名称需要在数据库中。

但是我如何才能找到所有具有流派 ID 的节目。

我找不到任何方法来获取该列表。 请帮忙,谢谢。

编辑:

这是shows_genres db 表

你应该这样做:

有一个类型的模型

你在 Genre 模型中的关系方法应该是

public function shows()
    {
        return $this->belongsToMany('App\Show', 'shows_genres');
    }

如果不是标准名称,则belongsToMany 接受两个参数,模型和数据透视表名称。

您的解决方案:

    //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();

默认情况下,数据透视表名称必须是单数:show_genre(没有复数)

查看文档

假设你在你的流派模型中有这种关系

public function shows()
{
   return $this->belongsToMany('App\Show', 'shows_genres', 'genre_id', 'show_id');
}

然后你可以像这样按流派ID直接获取所有节目

$shows = Genre::find($id)->shows;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM