【问题标题】:Many to many relationship check多对多关系检查
【发布时间】:2016-02-13 14:12:13
【问题描述】:

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

【问题讨论】:

    标签: laravel eloquent lumen


    【解决方案1】:

    您可以向模型添加方法。例如,在您的 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.
    }
    

    【讨论】:

      【解决方案2】:

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

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

      要获取客户详细信息,

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

      【讨论】:

      • 虽然使用关系的建议很好,但您的示例创建了one-to-many 关系,而 OP 明确指出该关系应为 many-to-many。这将要求使用的方法是belongsToMany,而不是hasMany
      猜你喜欢
      • 2011-02-23
      • 2020-10-23
      • 1970-01-01
      • 2021-11-12
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多