2017-08-08 148 views
1

使用Laravel 5.4,我有一個表和另一個表匹配 每場比賽都有隊主場ID隊客場IDLaravel - 合併兩個關係給出了一個錯誤

我發現這在這種情況下合併以尋找球隊在主場或客場比賽中所有比賽的絕妙好處。但它似乎並不奏效。

Laravel merge reltationships

/** 
* The matches that this team has played at home. 
*/ 
public function matchesHome() 
{ 
    return $this->hasMany('App\Match', 'team_home_id', 'id'); 
} 

/** 
* The matches that this team has played away. 
*/ 
public function matchesAway() 
{ 
    return $this->hasMany('App\Match', 'team_away_id', 'id'); 
} 

/** 
* The matches that this team has played. 
*/ 
public function matches() 
{ 
    $matchesPlayedHome = $this->matchesHome(); 
    $matchesPlayedAway = $this->matchesAway(); 

    // Merge collections and return single collection. 
    return $matchesPlayedHome->merge($matchesPlayedAway);  // cannot get this to work | Call to undefined method Illuminate\Database\Query\Builder::merge() 
} 

我得到的錯誤是調用未定義功能合併 調用未定義的方法照亮\數據庫\查詢\生成器::合併()

請幫助 謝謝

..................

我甚至試過預先加載,在這種情況下,誤差變

關係方法必須返回類型照亮\數據庫的對象\ \關係

public function matches() 
{ 
    $matches = Team::with('matchesHome', 'matchesAway')->get(); 
    return $matches; 
} 
+0

可能重複[無法在Laravel的Eloquent集合上合併](https://stackoverflow.com/questions/33654225/cannot-merge-on-an-eloquent-collection-in-laravel) –

回答

0

我覺得口才\關係你的語法是bit off:

function matches() { 
    return $this->matchesHome->merge($this->matchesAway); 
} 
+0

現在的錯誤是**關係方法必須返回Illuminate \ Database \ Eloquent \ Relations \ Relation **類型的對象** – Sallu

1

這就是我解決問題的方法。 The $ appends在另一篇文章中的答案尚不清楚,下面讓我解釋一下。

如果不添加任何方法來$追加,Laravel認爲,這也有關係屬性,並給出了一個錯誤關係方法必須返回類型照亮\數據庫\雄辯\關係的對象\關係

因爲它正在尋找它沒有得到的關係。這就是爲什麼如果我們添加$追加我們可以有以下代碼工作。

如果有人遇到這種情況,我就是這樣解決的。

protected $appends = ['matches']; 

/** 
* The matches that this team has played at home. 
*/ 
public function matchesHome() 
{ 
    return $this->hasMany('App\Match', 'team_home_id', 'id'); 
} 

/** 
* The matches that this team has played away. 
*/ 
public function matchesAway() 
{ 
    return $this->hasMany('App\Match', 'team_away_id', 'id'); 
} 


/** 
* This function is used by the appends to append two attributes 
*/ 
public function getMatchesAttribute() 
{ 
    return $this->matchesHome->merge($this->matchesAway); 
} 

我們也可以用Eager加載替換它,它會正常工作。