首页 > 解决方案 > 使用 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 的节目。

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

编辑:

这是 show_genres 数据库表

标签: laraveleloquenteloquent-relationship

解决方案


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


推荐阅读