更新时间:2023-12-04 08:15:10
尝试getter方法属性返回从关系返回的合并集合。
public function getCompetitionsAttribute($ value)
{
/ /有两个调用返回集合
//在关系中定义。
$ competitionsHome = $ this-> competitionsHome;
$ competitionitionsGuest = $ this-> competitionsGuest;
//合并集合并返回单个集合。
return $ competitionsHome-> merge($ competitionitionsGuest);
}
或者您可以在收集返回之前调用其他方法来获取不同的结果集。
public function getCompetitionsAttribute($ value)
{
//有两个调用返回集合
//在关系中定义。
//`latest()`方法是orderBy('created_at','desc')'
//方法调用的缩写。
$ competitionsHome = $ this-> competitionsHome() - > latest() - > get();
$ competitionsGuest = $ this-> competitionsGuest() - > latest() - > get();
//合并集合并返回单个集合。
return $ competitionsHome-> merge($ competitionitionsGuest);
}
Is there a way to merge 2 relationships in laravel?
this is the way it's setup now, but Is there a way I could return both merged?
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
}
Try out getter method for property which returns merged collections returned from relations.
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);
}
Or you can call additional methods before collection is returned to get different result sets.
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);
}