mercredi 25 novembre 2015

Laravel relationship null foreign key fetching

Since a team_id is optional in my tickets table, i've set it to be nullable but still is a foreign key to teams table, but when i try to fetch multiple rows of ticket with relationship to teams table, tickets that has team_id returns properly but tickets that has null team_id breaks the program and returns this error "Trying to get property of non-object".

Migration:

Schema::create('tickets', function (Blueprint $table) {
    $table->integer('team_id')->unsigned()->nullable();
});

Schema::table('tickets', function (Blueprint $table) {
    $table->foreign('team_id')
          ->references('id')
          ->on('teams');
});

Ticket model

public function team()
{
    return $this->belongsTo('App\Models\Team', 'team_id', 'id');
}

Team model

public function tickets()
{
    return $this->hasMany('App\Models\Ticket', 'id', 'team_id');
}

Ticket controller

$tickets = Ticket::orderBy('created_at', 'desc')
    ->take(10)
    ->get();

foreach ($tickets as $ticket) {
   var_dump($ticket->team->name);
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire