如何合并hasMany关系并在Laravel中返回一段关系?

时间:2018-06-14 19:16:47

标签: php laravel

我正在尝试合并2个集合,因为我需要搜索多个列中的记录team_one_idteam_two_id,具体取决于它是一个客场比赛还是主场比赛。

当尝试合并它们时,会在函数matches中发生这种情况。当我在第一个关系上调用merge时,函数matches不会返回实际关系,而是返回一个集合。

例外:

SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select count(*) as aggregate from `matches` where `matches`.`team_one_id` = 1 and `matches`.`team_one_id` is not null and `winning_team_id` = 1) union (select * from `matches` where `matches`.`team_two_id` = 1 and `matches`.`team_two_id` is not null))

代码:

<?php

namespace App\Database;

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
    protected $primaryKey = 'id';

    protected $table = 'teams';
    public $timestamps = false;
    protected $guarded = ['id'];

    public function homeMatches() {
        return $this->hasMany('App\Database\Match', 'team_one_id');
     }

     public function awayMatches() {
        return $this->hasMany('App\Database\Match', 'team_two_id');
     }

     public function matches() {
        return $this->homeMatches()->union($this->awayMatches()->toBase());
     }
}

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

 public function matches() {
    return $this->getRelationValue('homeMatches')->union($this->getRelationValue('awayMatches')->toBase());
 }

由于homeMatches()函数返回一个Relation实例,但动态属性返回一个Collection。

答案 1 :(得分:0)

Eloquent Relationships不是为了匹配一个或另一个字段而设计的,它们被设计为具有一个外键。您可以在方法中运行查询,以获得所需的结果,而无需依赖关系。

如评论中所述,如果要重新使用该查询,请在受保护的函数中包含该逻辑。

 protected function allMatchesQuery()
 {
     // This needs to be wrapped in a nested query or else your orWhere will not be contained in parentheses.
     return Match::where(function($q) { 
          $q->where('team_one_id', $this->id)->orWhere('team_two_id', $this->id);
     });
 }

 public function getMatches() {
    return $this->allMatchesQuery()->get();
 }


 public function getRecentMatches() {
    return $this->allMatchesQuery()->orderBy('date', 'DESC')->limit(10)->get();
 }