Laravel - 合并两个关系会出错

时间:2017-08-08 08:36:51

标签: php laravel-5

使用Laravel 5.4,我有一个表团队和另一个表匹配 每场比赛都有 TEAM HOME ID TEAM AWAY ID

我发现在这种情况下合并这个很棒的技巧,以找到一个球队在主场或客场比赛所发挥的所有比赛。但它似乎没有用。

Laravel merge reltationships

/**
 * The matches that this team has played at home.
 */
public function matchesHome()
{
    return $this->hasMany('App\Match', 'team_home_id', 'id');
}

/**
 * The matches that this team has played away.
 */
public function matchesAway()
{
    return $this->hasMany('App\Match', 'team_away_id', 'id');
}

/**
 * The matches that this team has played.
 */
public function matches()
{
    $matchesPlayedHome = $this->matchesHome();
    $matchesPlayedAway = $this->matchesAway();

    // Merge collections and return single collection.
    return $matchesPlayedHome->merge($matchesPlayedAway);     // cannot get this to work | Call to undefined method Illuminate\Database\Query\Builder::merge()
}

我得到的错误是调用未定义的函数合并     调用未定义的方法Illuminate \ Database \ Query \ Builder :: merge()

请帮忙 感谢

..................

我甚至尝试过加载,在这种情况下错误变为

关系方法必须返回类型为Illuminate \ Database \ Eloquent \ Relations \ Relation

的对象
public function matches()
{
    $matches = Team::with('matchesHome', 'matchesAway')->get();
    return $matches;
}

2 个答案:

答案 0 :(得分:1)

这就是我解决问题的方法。 另一篇文章中的 $追加答案尚不清楚,请让我在下面解释一下。

如果你没有向 $ appends 添加任何方法,Laravel认为它也是一个关系属性并给出错误关系方法必须返回一个类型为Illuminate \ Database \的对象口才\关系\关系

因为它正在寻找一种它没有得到的关系。这就是为什么如果我们添加 $ appends ,我们可以使用以下代码。

如果有人遇到这种情况,我就是这样解决的。

protected $appends = ['matches'];

/**
 * The matches that this team has played at home.
 */
public function matchesHome()
{
    return $this->hasMany('App\Match', 'team_home_id', 'id');
}

/**
 * The matches that this team has played away.
 */
public function matchesAway()
{
    return $this->hasMany('App\Match', 'team_away_id', 'id');
}


/**
 * This function is used by the appends to append two attributes
 */
public function getMatchesAttribute()
{
    return $this->matchesHome->merge($this->matchesAway);
}

我们也可以用Eager加载替换它,它会正常工作。

答案 1 :(得分:0)

我认为你的语法有点偏差:

function matches() {
  return $this->matchesHome->merge($this->matchesAway);
}