【问题标题】:Laravel 4: Many to Many with extra relationshipLaravel 4:具有额外关系的多对多
【发布时间】:2013-11-14 22:42:27
【问题描述】:

我遇到了 Laravel 4 和“多对多”查询关系的问题。 我有四张桌子:

  1. 用户
  2. 需要
  3. 货币
  4. user_needs

User_Needs 包含用户和需求之间的“多对多”关系。描述如下

id - user_id - need_id - currency_id - price

ID 是自动增量,PK 等等... user_id 是用户表的外键,need_id 是需求表的外键,currency_id 是货币表的外键。价格是浮动的。

在 Laravel 4 Models 文件夹中,我创建了以下模型

User,在 Model 类文件中使用 belongsToMany 函数:

public function needs()
{
return $this->belongsToMany('Need','user_needs','user_id','need_id')->withPivot('price');
}

需要为 belongsToMany 提供一个函数

public function users()
{
    return $this->belongsToMany('User','user_needs','user_id','need_id')->withPivot('price');
}

如果我只使用这两个模型,一切正常,问题是我必须添加“currency_id”,因为每个用户都可以为每个需求设置货币,我不知道如何更新我的模型来做它。目前我的货币模型没有 BelongsToMany,因为我不知道如何实现它。

Laravel 文档避免了“如何用多对多连接 3 个表”的话题,这有点烦人......

编辑:如果可能找到没有像 UserNeeds 这样的 中间模型 的解决方案,那将是 grate

感谢您的帮助。

【问题讨论】:

    标签: php mysql sql laravel-4 eloquent


    【解决方案1】:

    我在尝试将角色分配给用户/项目关系时遇到过这样的情况。

    您的 currency_id 应该只是 user_needs 数据透视表中的另一列,因为它是关系的属性。 (如你所愿)。

    使用 user_needs 表中的 currency_id 列,更新您的“withPivot”以包含 currency_id,您将获得查询用户需求关系时所需的所有数据。

    编辑:您还可以通过使用相同的 user_needs 表并在定义关系时指定所有内容来创建 Currency belongsToMany Users 关系。

    // in currency model
    
    return $this->belongsToMany('User', 'user_needs', 'user_id', 'currency_id');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2018-07-19
      • 2023-02-02
      • 1970-01-01
      • 2014-10-09
      相关资源
      最近更新 更多