且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel合并关系

更新时间:2023-12-03 23:49:28

尝试使用属性的getter方法,该方法返回从关系返回的合并集合.

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);
}