【问题标题】:Eloquent Relation - Relation of a Relation雄辩的关系 - 关系的关系
【发布时间】:2014-08-27 07:23:03
【问题描述】:

我有三个表:User、Client、Position。工作流程如下:

  1. client 创建自己的一组positions。
  2. client 将users 添加到其管理中,然后将positions 分配给它们
  3. 一个user可以属于多个不同的clients。

所以这些表之间的关系是:

  • Client 到 Position :一对多
  • Position 到 User :多对多
  • Client 到 User :多对多

所以目前,我的模型如下:

Class User extends Eloquent {
    public function clients() 
    {
        return $this->belongsToMany('Client');
    }

    public function positions() 
    {
        return $this->belongsToMany('Position');
    }
}

Class Client extends Eloquent {
    public function users() 
    {
        return $this->belongsToMany('User');
    }

    public function positions() 
    {
        return $this->hasMany('Position');
    }
}

// The Position model is not included, since it doesn't make sense to start from a position

所以,假设一个User 属于两个Clients,它们对于每个Clients 都有不同的Positions。一个例子是:

  • 我有两个客户:Sony 和 Microsoft
  • 我有两个用户:John 和 Mike。
  • Microsoft 拥有以下职位:开发人员和工程师。
  • Sony 的职位:营销和财务。
  • John 在 Microsoft 担任开发人员。
  • Mike 在 Microsoft 担任工程师,在 Sony 担任财务人员。

我只想获得 Mike 在 Microsoft 的职位。目前,我知道如何做到这一点的唯一方法如下:

$c_id = $Microsoft_Id;
$u_id = $Mike_Id;
Client::find($c_id)
        ->users()
        ->whereId($u_id)
        ->with(['positions' => function($query) use ($c_id) 
               {
                   $query->whereClientId($c_id);
               }
        ])
        ->get();

有没有办法可以在模型本身内执行此任务?如果我只想说,这会更直观:

Client::find($c_id)
        ->users()
        ->whereId($u_id)
        ->with('positions')
        ->get();

并且检查是在模型本身内执行的。

【问题讨论】:

  • 再次使用 3 个模型之间的 m-m 关系是有意义的。如果没有Client 的上下文,您似乎无法查询User 的Position,不是吗?
  • 是的,但是由于我已经使用$c_id 和$u_id 查询过它,我试图从关系内部的$this 访问该信息,然后限制返回的值.
  • 一个用户可以在一个客户拥有多个职位?
  • 是的,一个用户可以在任何给定的客户上拥有多个职位。
  • 那就无视我之前的建议,查看答案

标签: laravel laravel-4 eloquent relationship


【解决方案1】:

你可以使用它,但是在急切加载时它不起作用,因为显然$id 将无法访问:

// Client model
public function usersWithPositions()
{
    $id = $this->getKey();

    return $this->belongsToMany('User')->with(['positions' => function ($q) use ($id) {
        $q->whereClientId($id);
    }]); 
}

// will work
$client = Client::find($c_id);
$client->usersWithPositions;
// or
$Mike = $client->usersWithPositions()->where('users.id', $u_id)->first();


// won't work
Client::with('usersWithPositions')->get();

您可以在此方法中添加检查,这样它就不会抛出异常,但它仍然无法与预加载一起工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2015-03-14
    • 2018-11-28
    相关资源
    最近更新 更多