2015-08-28 79 views
1

我想在一個Model方法中合併兩個hasMany關係。這兩種關係幾乎完全相同,唯一的區別是外鍵。如何從同一個表中合併兩個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 
    } 
} 
+0

根據定義,一個模型/表格只有一個標識符,它看起來好像Friend模型會有兩個標識符......甚至可能嗎? – Amarnasan

+0

也許這是有幫助的:http://stackoverflow.com/questions/24184069/laravel-merge-reltationships – Amarnasan

+0

@Amarnasan是我也發現了這個問題,但是這並沒有解決我的問題,因爲它在兩個集合合併爲一個單一集合意味着我無法再對其調用查詢方法。 – Zero

回答

1

我知道這是可怕的,但...考慮將您的合併收集到一個像這樣的新查詢:

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

除了這個解決方案導致另一個數據庫查詢,由於主鍵查找,性能損失不會太高。至少這是一個省力的解決方法。 – Zero