2

我有两个模型用户和孩子。

class User extends Model {
  public function children() {
    return $this->belongsToMany('App\Child', 'user_child')->withPivot('relation_id');
  }
  public function connections() {
    // How to get the distinctly aggregate of my children.friends.contacts as a relationship here?
  }
}

class Child extends Model {
  public function contacts() {
    return $this->belongsToMany('App\User', 'user_child')->withPivot('relation_id');
  }
  public function friends() {
    return $this->belongsToMany('App\Child', 'child_connection', 'child_id1', 'child_id2');
  }
}

我想急切地加载我称之为“连接”的远距离关系,它们是我孩子朋友的联系人(用户)。

$user = User::with('children', 'children.friends', 'connections');

任何想法如何优雅地做到这一点?

谢谢!

4

1 回答 1

1

尝试

public function connections() {
    return $this->belongsToMany('App\Child', 'user_id')->with('friends.contacts;);
}

天哪!如果有任何奇迹,那么做

$user = User::find(1);
$user->connections(); //should bring 'children', 'friends' and 'contacts' in one query.

那么它应该。

如果您找到答案,请发布它。我对这个真的很感兴趣。

于 2017-02-16T03:33:49.733 回答