普通网友 2014-09-01 20:00
浏览 15
已采纳

Laravel - 相同的模型通过另一个相关

I'm having trouble finding the appropriate documentation on this.

I'm have a User model, each User can have a many to many relationship with a Site. I am trying to find out how to get the relationships between Users.

For example, one User might be the Site owner, and the other could be the Client. If I have the owner object, how can I retrieve an array of Clients, associated with all, or individual Sites.

I've tried using

public function clients() {
    return $this->hasManyThrough('User', 'Site');
}

However this still returns the current user which I'm unable to filter out.

I'm not sure if I have my models wrong, e.g. needing to have an Owner and a Client model, which both extend a generic User.

Any help would be appreciated.

Thanks.

  • 写回答

1条回答 默认 最新

  • duanchi5078 2014-09-02 17:24
    关注

    Your models are probably fine. You are using many-to-many relation, so good place for specifying the type of that relation would be that same table - pivot table.

    users
      id
      name
    
    sites
      id
      url
    
    site_user
      site_id
      user_id
      type
    

    where type is for example string owner or client.

    class User extends Eloquent {
      public function sites() {
        return $this->belongsToMany('Site')
                    ->withPivot('type');
      }
    }
    class Site extends Eloquent {
      public function users() {
        return $this->belongsToMany('User')
                    ->withPivot('type');
      }
      // you can use something like this 
      public function clients(){
        return $this->users()->wherePivot('type', 'client');
      }
    }
    

    Once you have the site you want, you can then get clients like this

    $clients = $site->clients()->get();
    

    hope this get you in right direction (away from creating more models, trying to figure out inheritance, dealing with the Factory pattern etc... ). sometimes solutions are simple, and from my experience - when you start to over-complicate the models (in this manner), there is a good chance that something is wrong with your database design.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序