jmitnik@gmail.com's avatar

Relationship model hasMany() returns an empty array

Hi guys,

I have been struggling with figuring out why an empty array gets returned whenever I execute in my php artisan tinker the following command:

$team = App\Team::get()[5]->events;

The primary key is set to team_name, I feel that this is what makes this not work.

What gets returned is an empty Collection array, but considering my users events has been filled with a number of fake models which also have entries(matching teams) in table events, something should be off in the configuration I think My migrations for my team and event table are according to the following code:

For table Events:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->increments('id');
            $table->time('round_time');
            $table->integer('machine_id');
            $table->string('team_name');
            $table->foreign('team_name')->references('team_name')->on('teams');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('events');
    }
}

For table teams:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTeamsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('teams', function (Blueprint $table) {
            $table->string('team_name')->primary();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('teams');
    }
}

The model code for both are:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    //
    //
    
    public function team()
    {
        return $this->belongsTo('App\Team', 'team_name', 'team_name');
    }

    // public function round()
    // {
    //  return $this->belongsTo('App\Round', 'event_id');
    // }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;

class Team extends Model
{
    //
    protected $primaryKey = 'team_name';

    public function events()
    {
        return $this->hasMany('App\Event', 'team_name', 'team_name');
    }
}

0 likes
1 reply
jmitnik@gmail.com's avatar
Level 2

Nevermind, found the fix: I had forgotten to set incrementing on my Team model to false, considering the primary key of table teams is a string(team_name) and not an incrementing value such as ID.

    public $incrementing = false;

Please or to participate in this conversation.