【问题标题】:Laravel - Merge Two Relationship gives an errorLaravel - 合并两个关系给出错误
【发布时间】:2018-01-15 17:31:12
【问题描述】:

使用 Laravel 5.4,我有一个表 Teams 和另一个表 Matches 每场比赛都有TEAM HOME IDTEAM 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()
}

我得到的错误是 Call to undefined function merge 调用未定义的方法 Illuminate\Database\Query\Builder::merge()

请帮忙 谢谢

........

我什至尝试过预先加载,在这种情况下错误变成了

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

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

【问题讨论】:

标签: php laravel-5


【解决方案1】:

我觉得你的语法有点不对:

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

【讨论】:

  • 现在的错误是 Relationship 方法必须返回 Illuminate\Database\Eloquent\Relations\Relation 类型的对象
【解决方案2】:

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

如果不给$appends添加任何方法,Laravel认为也是关系属性,报错Relationship method must return an object of type 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 loading 替换它,它会正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 2019-12-15
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多