代码之家  ›  专栏  ›  技术社区  ›  mps

Laravel hasOne具有两个匹配字段

  •  1
  • mps  · 技术社区  · 1 年前

    我需要建立一个 hasOne 同时匹配两个字段的关系。

    这是我的 users 桌子

    身份证件 使用者 conc 名称
    1. JDoe 基础知识 John Doe
    2. JDoe ZXC John Doe

    这是我的 membership 桌子

    身份证件 使用者 conc 角色
    1. JDoe ZXC 管理

    为了使用中需要关系的另一个组件 会员 模型,我需要同时使用两个标准: user conc 。预期结果是:

    $memb = Membership::find(1);
    $memb->user; // This should return the user with ID 2, since it has the same 'user' and 'conc'
    

    我试过使用 ->ofMany ,但我似乎需要一个 join 不止一个 where ,我无法让它工作。

    编辑:中永远不会有两条记录 用户 相同的表 使用者 conc ,因此 hasOne 而不是 hasMany 关系

    1 回复  |  直到 1 年前
        1
  •  1
  •   Karl Hill    1 年前

    您可以定义 hasOne 使用与多个条件的关系 where 关系定义中的子句。以下是如何在 Membership 模型

    public function user()
    {
        return $this->hasOne(User::class, 'user', 'user')
            ->where('conc', $this->conc);
    }
    

    然后,您可以访问相关的 User 来自的模型 会员 模型实例,例如以下。

    $memb = Membership::find(1);
    $user = $memb->user; // This will return the User model with the same 'user' and 'conc' as the Membership model
    
    推荐文章