本文介绍了Laravel合并关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在laravel中合并2个关系?这是现在安装的方式,但是有没有办法可以返回两者合并? p>
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&竞争对手
}
解决方案
尝试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);
}
这篇关于Laravel合并关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!