Tuesday, March 21, 2017

Eloquent doesn't retrive the belongsTo relation

I have a publication model which belongs to an author represented by the user model. This is how they are defined :

class Publication extends \Illuminate\Database\Eloquent\Model {
  public $incrementing = false;

  public function author() {
    return $this->belongsTo('App\Models\User');
  }
}

I used the standard naming conventions in my tables, so in the publications table I have a column nammed user_id.

class User extends \Illuminate\Database\Eloquent\Model {
  const ROLES = ["Enseignant-Chercheur", "Doctorant"];

  public $incrementing = false;

  public function publications() {
    return $this->hasMany('App\Models\Publication');
  }
}

When I try to retrive my data :

$publications = \App\Models\Publication::orderBy('created_at', 'desc')->take(10)->get();
die('<pre>'.var_export($publications[0], true).'</pre>');

The relations array is empty... In the database, the row is correctly filled with the right user id.
How to fix this ?



via Wizix

Advertisement