多对多关系检查

时间:2015-11-12 09:37:29

标签: laravel eloquent lumen

我有两个模型,User和Client,它们应该是多对多的关系。我是lumen / laravel的新手,所以我想知道检查用户是否属于客户端的正确方法是什么?假设我有一个$ client和用户$ user模型,我应该写什么样的雄辩查询来检查$ user是否属于$ client?

2 个答案:

答案 0 :(得分:0)

在您的客户端模式中添加hasMany关系

public function client(){
    return $this->hasMany('App\Client');
}

要获取客户详细信息,

$users = User::first();
print_r($users->client);

答案 1 :(得分:0)

您可以为模型添加方法。例如,在用户模型中,您可以创建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.
}
相关问题