有没有办法在laravel中合并2个关系?
这是现在设置的方式,但是有没有办法我可以将两者合并?
public function CompetitionsHome() { return $this->HasMany( 'Competition', 'home_team_id' ); } public function CompetitionsGuest() { return $this->HasMany( 'Competition', 'guest_team_id' ); } public function Competitions() { // return both CompetitionsHome & CompetitionsGuest }
试用属性的getter方法,该方法返回从关系返回的合并集合。
public function getCompetitionsAttribute($value) { // There two calls return collections // as defined in relations. $competitionsHome = $this->competitionsHome; $competitionsGuest = $this->competitionsGuest; // Merge collections and return single collection. return $competitionsHome->merge($competitionsGuest); }
或者,您可以在返回集合之前调用其他方法以获取不同的结果集。
public function getCompetitionsAttribute($value) { // There two calls return collections // as defined in relations. // `latest()` method is shorthand for `orderBy('created_at', 'desc')` // method call. $competitionsHome = $this->competitionsHome()->latest()->get(); $competitionsGuest = $this->competitionsGuest()->latest()->get(); // Merge collections and return single collection. return $competitionsHome->merge($competitionsGuest); }