Laravel所属的关系返回null?

时间:2019-01-20 14:27:39

标签: php laravel

我正在尝试获取今天安排的比赛,但似乎我的关系无法正常工作并返回null。

我如何获取今天的比赛:

$scheduledMatches = ClanMatch::whereDate('created_at', Carbon::today())->get(); 
// ->count() of the above line is 0 if I add 'has('homeClan', 'awayClan')'

到底是什么返回空值?

$firstMatch = $scheduledMatches->first();
dd($firstMatch->homeTeam); // returns null

此外,当尝试foreach $scheduledMatches时,当我尝试访问的字段为空($ scheduledMatches中的记录)时,它会抛出空错误。

我怎么知道它实际上不为空?

$firstMatch = $scheduledMatches->first();
$clan = Clan::find($firstMatch->home_team); // exists

这是ClanMatch模型:

class ClanMatch extends Model
{
    protected $table = 'clan_matches';

    public function homeTeam() {
        return $this->belongsTo('App\Clan', 'home_clan');
    }

    public function awayTeam() {
        return $this->belongsTo('App\Clan', 'away_clan');
    }
}

根据要求创建氏族模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\ClanMatches;

class Clan extends Model
{
    public function homeMatches() {
        return $this->hasMany('App\ClanMatch', 'home_clan');
    }

    public function awayMatches() {
        return $this->hasMany('App\ClanMatch', 'away_clan');
    }

    public function matches() {
        return ClanMatch::where('home_clan', $this->id)->orWhere('away_clan',$this->id);
    }  

    public function points() {
        return ($this->matchesWon()->count() * 3) + $this->matchesDrawn()->count();
    }

    public function seasons()
    {
        return $this->belongsToMany(Season::class);
    }

    public function tournaments() {
        return $this->belongsToMany(Tournament::class);
    }
}

迁移(表结构)

// clans table
Schema::create('clans', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('tag');
    $table->string('logo');
});

// clan matches table
Schema::create('clan_matches', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('tournament_id');
    $table->integer('home_clan');
    $table->integer('home_score');
    $table->integer('away_clan');
    $table->integer('away_score');
    $table->integer('mode');
    $table->integer('map');
    $table->enum('participants', [4,5,6]);
    $table->timestamp('scheduled_for');
    $table->timestamps();
});

2 个答案:

答案 0 :(得分:0)

您可以打印以下代码:

ClanMatch::with('homeTeam', 'awayTeam')
           ->whereDate('created_at', Carbon::today())
           ->toSql(); 

,然后在 phpmyadmin 或其他数据库程序中检查结果。

答案 1 :(得分:0)

一些调试技巧:

确保您的迁移是这样的

clan_matches
    $table->increments('id');

clans
    $table->unsignedInteger('home_team')->nullable();
    $table->unsignedInteger('away_team')->nullable();
    $table->foreign('home_team')->references('id')->on('clan_matches');
    $table->foreign('away_team')->references('id')->on('clan_matches');

现在确保您的表中有一些数据,例如

clan_matches
id|name|
1|home
2|away

clans
id|name|home_team|away_team
1|home|1|null
2|away|2|null

现在这应该返回您的结果