【问题标题】:Aggregate distant relationship with eloquent用口才聚合远方的关系
【发布时间】:2017-07-04 23:41:35
【问题描述】:

我有两个模型 User 和 Child。

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');

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

谢谢!

【问题讨论】:

    标签: php laravel eloquent lumen laravel-eloquent


    【解决方案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.
    

    嗯,应该的。

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

    【讨论】:

    • 我将其更改为“children.friends.contacts”,但仍然没有给出正确的结果。我只想要我孩子朋友的联系方式。不过感谢您的努力!
    猜你喜欢
    • 2018-05-18
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 2020-05-09
    • 2016-03-28
    • 2014-02-08
    相关资源
    最近更新 更多