php Laravel关系错误:hasMany闭包函数中的变量$homeTeam未定义

a64a0gku  于 2023-03-07  发布在  PHP
关注(0)|答案(1)|浏览(146)

我正在处理一个Laravel应用程序,其中有一个Matches模型,该模型具有一个homeHistory关系,该关系返回主队的比赛历史记录。我正在尝试在查询中将此关系与homeTeam和awayTeam关系一起快速加载。
我在Matches模型中定义了homeHistory关系,如下所示:

public function homeHistory()
{
    return $this->hasMany(History::class, function ($query) {
        $query->where(function ($subquery) {
                $subquery->where('home_team_id', $this->homeTeam->id)
                    ->orWhere('away_team_id', $this->homeTeam->id);
            })
            ->orderBy('date_of_match', 'desc')
            ->limit(5);
    });
}

我渴望在我的控制器中加载查询中的关系,如下所示:

$leagues = Leagues::with([
    'matches' => function ($query) {
        $query->whereDate('date_of_match', '=', now()->toDateString())
            ->orderBy('date_of_match', 'asc')
            ->orderBy('time_of_match', 'asc')
            ->limit(10)
            ->with([
                'odds', 
                'homeTeam', 
                'homeHistory' => function ($query) {
                    $query->homeTeam();
                }
            ]);
    }, 
    'matches.homeTeam', 
    'matches.awayTeam'
])
->whereHas('matches', function ($query) {
    $query->whereDate('date_of_match', '=', now()->toDateString());
})
->get();

但是,当我运行查询时,我得到一个错误,在homeHistory关系闭包函数中显示"Undefined variable $homeTeam"。
我很困惑为什么会发生这个错误,因为我已经在急切地加载homeTeam关系了。我如何修复这个错误并正确地急切地加载homeHistory关系?

    • 编辑:**

以下是历史模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use App\Models\Team;

class History extends Model
{
    protected $table = "history";
    protected $fillable = [
        "home_team_id",
        "away_team_id",
        "home_score",
        "away_score",
        "league_name",
        "date_of_match",
        // 'form'
    ];

    public function homeTeam()
    {
        return $this->belongsTo(Teams::class, "home_team_id");
    }

    public function awayTeam()
    {
        return $this->belongsTo(Teams::class, "away_team_id");
    }

    public function scopeTeamHistory($query, $teamId)
    {
        return $query
            ->where(function ($query) use ($teamId) {
                $query
                    ->where("home_team_id", $teamId)
                    ->orWhere("away_team_id", $teamId);
            })
            ->latest()
            ->limit(5);
    }
}

下面是匹配模型:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Teams;
use App\Models\History;
use App\Models\Odds;
use App\Models\LatestScores;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class Matches extends Model
{   
    public function odds()
    {
        return $this->hasMany(Odds::class, "match_id");
    }

    public function homeTeam()
    {
        return $this->belongsTo(Teams::class, "home_team");
    }

    public function awayTeam()
    {
        return $this->belongsTo(Teams::class, "away_team");
    }

    public function homeHistory($homeTeam)
    {
        return $this->hasMany(History::class, function ($query) use (
            $homeTeam
        ) {
            $query
                ->where(function ($subquery) use ($homeTeam) {
                    $subquery
                        ->where("home_team_id", $homeTeam->id)
                        ->orWhere("away_team_id", $homeTeam->id);
                })
                ->orderBy("date_of_match", "desc")
                ->limit(5);
        });
    }
}

匹配表的架构:

Schema::create('matches', function (Blueprint $table) {
    $table->increments('id');
    
    $table->integer('home_team')->unsigned()->nullable();
    
    $table->integer('away_team')->unsigned()->nullable();
    
    
    $table->boolean('important')->default(0);
    
    $table->date('date_of_match')->nullable();
    $table->timestamp('time_of_match')->nullable();
    $table->integer('league_id')->unsigned()->nullable();
    $table->foreign('league_id')->references('id')->on('leagues');
    
    $table->timestamps();
});
2g32fytz

2g32fytz1#

给定Illuminate\Database\Eloquent\Concerns\HasRelationships trait中hasMany函数的原始定义,该语法应该无效。

/**
     * Define a one-to-many relationship.
     *
     * @param  string  $related
     * @param  string|null  $foreignKey
               ^^^^^^^^^^^^^^^^^^^^^^^^
     * @param  string|null  $localKey
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function hasMany($related, $foreignKey = null, $localKey = null)
    {
        $instance = $this->newRelatedInstance($related);

        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $localKey = $localKey ?: $this->getKeyName();

        return $this->newHasMany(
            $instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey
                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        );
    }

然而,假设这里有一个包在工作,我认为$this可能不是闭包执行时的模型。

$query->where(function ($subquery) {
    // sanity check dump(get_class($this), $this->homeTeam)); ?
    $subquery->where('home_team_id', $this->homeTeam->id)
        ->orWhere('away_team_id', $this->homeTeam->id);
})

相关问题