【发布时间】:2016-02-13 14:12:13
【问题描述】:
我有两个模型,用户和客户端,应该是多对多的关系。我是 lumen/laravel 的新手,所以我想知道检查用户是否属于 Client 的正确方法是什么?假设我有一个 $client 和 user $user 模型,我应该写什么样的雄辩的查询来检查 $user 是否属于 $client ?
【问题讨论】:
我有两个模型,用户和客户端,应该是多对多的关系。我是 lumen/laravel 的新手,所以我想知道检查用户是否属于 Client 的正确方法是什么?假设我有一个 $client 和 user $user 模型,我应该写什么样的雄辩的查询来检查 $user 是否属于 $client ?
【问题讨论】:
您可以向模型添加方法。例如,在您的 User 模型中,您可以创建一个 hasClient 方法。此方法可以接受客户端或客户端 ID。然后,它将遍历用户的所有客户端并检查传入的参数是否与用户的任何客户端匹配。
// Accepts the client's id or client
public function hasClient($id)
{
// If you pass in an instance of the client model,
// we will extract the id from that model
if ($id instanceof Model)
{
$id = $id->getKey();
}
// Loop through all of the user's clients and see if any match
foreach ($this->clients as $client)
{
if ($client->id == $id)
{
return true;
}
}
return false;
}
现在,假设您有一个用户和一个客户:
$user = User::first();
$client = Client::first();
您可以这样做来检查用户是否拥有该客户端:
if ($user->hasClient($client))
{
// User has client. Do something.
}
【讨论】:
在您的客户端模式下添加hasMany 关系,
public function client(){
return $this->hasMany('App\Client');
}
要获取客户详细信息,
$users = User::first();
print_r($users->client);
【讨论】:
belongsToMany,而不是hasMany。