Laravel合并关系

问题描述 投票:9回答:3

有没有办法合并laravel中的两个关系?

这就是它现在设置的方式,但是有没有办法让两者合并?

  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
  }
php laravel-4 eloquent relationships
3个回答
20
投票

尝试使用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);
}

5
投票

如果您更喜欢使用merge()方法来组合两个集合(关系),它将覆盖具有相同索引键的元素,因此您将丢失从一个关系中获得的一些数据。

您应该选择push()方法,通过将一个集合推送到其他集合的末尾来创建新的数组键

这是一个示例:

public function getCompetitionsAttribute($value) {
    $competitionsHome = $this->competitionsHome;
    $competitionsGuest = $this->competitionsGuest;

    // PUSH ONE TO OTHER!
    return $competitionsHome->push($competitionsGuest);
}

0
投票

如果由于谷歌而有人像我一样登陆这里:因为既没有merge()也没有push()允许急切加载(和其他好的关系功能),讨论并没有以这个线程结束,而是在这里继续:Laravel Eloquent Inner Join on Self Referencing Table

我提出了一个解决方案here,任何进一步的想法和对这个问题的贡献欢迎。

© www.soinside.com 2019 - 2024. All rights reserved.