繁体   English   中英

如何合并来自同一表的两个hasMany关系?

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

我想在一个Model方法中合并两个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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM