【问题标题】:Laravel Eloquent - Get entry of a table that BelongsToMany another TableLaravel Eloquent - 获取属于另一个表的表的条目
【发布时间】:2014-10-08 10:13:01
【问题描述】:

我有两个模型:ClientUser,每个模型之间的关系是belongsToMany

我想获取属于某个客户端的所有用户,并通过 ID 引用该客户端。我想不出我会怎么做,除非我以Client开头并使用with,即

$client = Client:find($client_id);
return $client->users();

但我不想得到客户。有没有办法直接获取用户?

之所以不想获取客户端,是因为我只想选择一些列,而根据this,它仍然不可用。即使我尝试它,它仍然会返回 all 列。

我的模型定义是:

客户端模型:

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

用户模型:

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

【问题讨论】:

  • 向我们展示您在模型中的关系定义,请
  • @pc-shooter,我做到了。但它是非常基本的单行代码
  • 如果您想要所有用户,您肯定需要从客户端开始吗?在这种情况下,只需执行$users = Client::find($client_id)->users;
  • @MartinBean,是的,这正是我上面所说的。但是,我想选择用户的特定列,由于 belongsToMany 不允许你这样做,我不想参考 Client
  • 这么多用户属于许多客户,反之亦然?

标签: mysql laravel-4 eloquent


【解决方案1】:

您可以使用 Eloquent whereHas 或简单连接。

根据表的大小,一个或另一个在性能方面会更好。

whereHas方法:

User::whereHas('clients', function($q) use($clientId) {
  $q->where('clients.id', $clientId);
})->get([ .. columns to select ..]);

join:

User::join('client_user as cu', 'cu.user_id', '=', 'users.id')
  ->where('cu.client_id', $clientId)
  ->get([ .. your columns to selects .. ]);

或者,如果您不能确定数据透视表上的数据一致性,也可以加入相关表:

User::join('client_user as cu', 'cu.user_id', '=', 'users.id')
  ->join('clients as c', 'cu.client_id', '=', 'c.id')
  ->where('c.id', $clientId)
  ->get([ .. your columns to selects .. ]);

【讨论】:

    【解决方案2】:

    如果你真的只需要返回特定的列,你可以在流畅的查询生成器中使用get()

    $users = Client::find($client_id)
        ->users()
        ->get(array('id', 'name'));
    

    这将获取属于具有$client_id 指定的 ID 的客户端的所有用户的 ID 和名称列。

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      相关资源
      最近更新 更多