簡體   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