【问题标题】:Laravel - Same model related through anotherLaravel - 通过另一个相关的相同模型
【发布时间】:2014-09-03 01:24:10
【问题描述】:

我无法找到相关的文档。

我有一个User 模型,每个User 都可以与Site 建立多对多关系。我正在尝试找出如何获取Users 之间的关系。

例如,一个User 可能是Site 所有者,另一个可能是Client。如果我有所有者对象,我如何检索与所有或单个 Sites 相关联的 Clients 数组。

我尝试过使用

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

但是这仍然会返回我无法过滤掉的当前用户。

我不确定我的模型是否有误,例如需要拥有一个 Owner 和一个 Client 模型,它们都扩展了一个通用的 User。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • 如何知道用户是所有者还是客户?您是否将该信息存储在 User 表中?但是我不确定hasManyThrough 方法在这里是否合适,毕竟你没有中间关系。我宁愿使用belongsToMany,如下所述:laravel.com/docs/eloquent#many-to-many

标签: php laravel laravel-4 eloquent


【解决方案1】:

您的模型可能没问题。您正在使用多对多关系,因此指定该关系类型的好地方是同一张表 - 数据透视表。

users
  id
  name

sites
  id
  url

site_user
  site_id
  user_id
  type

其中类型例如是字符串 owner 或 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');
  }
}

一旦你有了你想要的网站,你就可以得到这样的客户

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

希望这能让您朝着正确的方向前进(远离创建更多模型、尝试找出继承、处理工厂模式等...)。有时解决方案很简单,但根据我的经验 - 当您开始(以这种方式)过度复杂化模型时,您的数据库设计很有可能出现问题。

【讨论】:

  • 这看起来正是我需要的,一个快速的问题,保存关联时如何指定类型?谢谢
  • $user->sites()->attach($site_id, array('type'=>'client'));
猜你喜欢
  • 2020-05-25
  • 2016-05-04
  • 1970-01-01
  • 2012-05-02
  • 2014-04-02
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
相关资源
最近更新 更多