gpt4 book ai didi

php - Laravel 合并关系

转载 作者:可可西里 更新时间:2023-10-31 22:07:44 24 4
gpt4 key购买 nike

有没有办法在 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);
}

关于php - Laravel 合并关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24184069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com