如何从同一个表合并两个hasMany关系?


How can I merge two hasMany relations from the same table?

我想在一个模型方法中合并两个hasMany关系。这两个关系几乎是相同的,唯一的区别是外键。

请注意,我不能简单地在两个关系上调用查询生成器get()方法,因为我必须处理合并的关系,而不是集合,例如,我想对合并的关系进行排序,或者在它上调用->where()

下面是一个示例代码:

Friend.php

<?php
class Friend extends Model
{
  /*
  Database structure:
  - id
  - user_id
  - friend_id
  */
  public function user()
  {
    return $this->belongsTo('App'Models'User');
  }
  public function friend()
  {
    return $this->belongsTo('App'Models'User', 'friend_id');
  }
}

User.php

<?php
class User extends Model
{
  /*
  Database structure:
  - id
  [...]
  */
  public function friends()
  {
    $friends_left = $this->hasMany('App'Models'Friend', 'friend_id');
    $friends_right = $this->hasMany('App'Models'Friend', 'user_id');
    // return single relation
  }
}

我知道这很糟糕,但是…考虑将合并集合转换为新的查询,如下所示:

    $collection1 = ...;
    $collection2 = ...;
    $collection = $collection1->merge($collection2);
    $values = $collection->lists('id');
    $query = User::whereIn('id',$values)->....and continue with your queries;