【问题标题】:How to connect 3 table but 2nd table is conjuction in Eloquent? and retrieve the data如何在 Eloquent 中连接 3 个表但第 2 个表是连词?并检索数据
【发布时间】:2021-03-31 21:57:32
【问题描述】:

如何用 2 个模型连接 3 个表?创建 media_genres 模型也会很尴尬。并检索标题和流派。

在流派表中有 1。动作,2 流派。在 Medias 表中有 1 部电影 生化危机。

它应该返回 2 行,因为我在 media_genres 表中使用该 ID 分配了 2 个流派。在底部,雄辩与流派无关。它只是返回而没有流派。

媒体表

Media_ID mediumIncrements // 1. Resident Evil
Title string 255
Synopsis text nullable

media_genres 表

Media_ID unsignedMediumInteger (foreign of medias table)
Genre_ID unsignedSmallInteger (foreign of genres table)

流派表

Genre_ID smallIncrements // 1. Action, 2. Drama
Genrename string 100 

媒体模型

protected $table = 'media';
public $timestamps = false;
protected $primaryKey = 'Media_ID';

public function genre()
{
    $this->hasOne(Media_Genre::class, 'Media_ID', 'Media_ID');
}

类型模型

protected $table = 'genre';
public $timestamps = false;
protected $primaryKey = 'Genre_ID';

Media_Genre 模型

protected $table = 'media_genres';
public $timestamps = false;

控制器

return Media::where('Media_ID', 1)->get();

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    要通过第三个数据透视表将媒体表与流派联系起来,请使用关系 belongsToMany

    public function genre()
    {
        return $this->belongsToMany(Genre::class, 'media_genres', 'media_id', 'genre_id');
    }
    

    然后在您的控制器中使用with 获取媒体及其类型。

    return Media::with('genre')->where('Media_ID', 1)->get();
    

    【讨论】:

    • 如何只返回table的值?结果它返回其他键,例如枢轴?
    • @davidstephen 你为什么要麻烦删除它们。他们是关系的一部分,这就是他们在那里的原因。如果要删除它们,请使用响应对象,在流派模型中使用 $hidden 属性或任何东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多