【问题标题】:using name column in belongsToMany relation instead of id在 belongsToMany 关系中使用 name 列而不是 id
【发布时间】:2018-01-24 09:10:02
【问题描述】:

我有两个模型,一个是报价(用于优惠表),另一个是品牌(用于品牌表)。这些模型之间存在“多对多”的关系。

我有一个表 offer_brands 来映射这两个表之间的关系。在这个表中,我有将这个表链接到 offer 表的 offer_id 列和将这个表链接到brands 表的brand 列usind brand_name 列在brands 表中。

在品牌模型中,我想要一个返回所有报价的关系。

我知道我可以做到

public function offers()
{
    return $this->belongsToMany(Offer::class, 'offer_brands', 'offer_id', 'brand_id'); // But don't have brand_id column insted I have brand column that contains brand names
}

我也试过了

public function offers()
{
    return $this->belongsToMany(Offer::class, 'offer_brands', 'offer_id', 'brand'); // But Eloquent compare this column with id column of brands table.
}

【问题讨论】:

    标签: mysql laravel eloquent laravel-eloquent


    【解决方案1】:

    以防万一有人仍在寻找答案.. 以下是解决此问题的方法。

    例如,我有用户角色。并且数据透视表 (@​​987654321@) 具有 user_id。但不是包含role_id,而是包含role 列,基本上是roles 表中角色的slug

    我可以完全像这样指定关系:

    public function roles()
    {
        return $this->belongsToMany('App\Role', 'team_users', 'user_id', 'role', 'id', 'slug');
    }
    

    基本上App\Role是关系模型。

    team_users 是数据透视表名称。

    user_id 是外键(所以在team_users 中会有一个名为user_id 的列)

    role 是相关的主键(所以在team_users 中会有一个名为role 的列)

    id 是父键(因此在App\User 中,Laravel 将在数据透视表中查找其id 列值等于外部数据透视键user_id 的行)。

    slug 是相关键(所以在App\Role 中,Laravel 会在数据透视表中查找slug 列值等于role 列的行)

    【讨论】:

    • 如果我可以点击 10 次,我会的。为我保命。谢谢。
    【解决方案2】:

    正确定义:

    return $this->belongsToMany(Offer::class, 'offer_brands', 'brand', 'offer_id');
    

    但使用命名约定是个好主意。您可以将表命名为brand_offer,并将外键命名为offer_idbrand_id。在这种情况下,关系将如下所示:

    return $this->belongsToMany(Offer::class);
    

    在我的最佳实践存储库中了解有关 Laravel naming conventions 的更多信息。

    【讨论】:

    • 这不是我的问题的答案。如果我成功地解释了问题中的问题,请告诉我。
    • @AmarjitSingh 你有错误的关系定义。而且您不能在其他模型的表中包含 FK,因为这不是多对多关系的工作方式。您是否尝试过在投票前复制并粘贴它?
    • 是的,我做到了,但出现错误未知列 offer.brand 和brands.offer_id
    • @AmarjitSingh 你不可能用这段代码得到这个错误。
    猜你喜欢
    • 2021-08-31
    • 2015-06-23
    • 1970-01-01
    • 2018-05-19
    • 2013-01-18
    • 2021-07-28
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    相关资源
    最近更新 更多