Louis Etienne
Louis Etienne

Reputation: 1371

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 ?

Upvotes: 0

Views: 73

Answers (2)

user4094161
user4094161

Reputation:

@Wizix You can try as below to retrieve relationship data using explicitly define foreign key if your foreign key not match with laravel mechanism.

//in Publication Model define relationship as below

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

// in user model define as below

public function publications() {
    return $this->hasMany('App\Models\Publication','user_id');
    //user_id consider as foriegn key in publication model's table
 }

then you can try accessing relationship data using "with" keyword using eloquent as below.

\App\Models\Publication::with('author')->orderBy('created_at', 'desc')->take(10)->get();

Upvotes: 2

dparoli
dparoli

Reputation: 9171

The relationship is loaded only if explicitly accessed, i.e.: $publications[0]->author

Or if you want you can eager load authors, and reduce the needed queries, with the function with():

\App\Models\Publication::with('author')->orderBy('created_at', 'desc')->take(10)->get();

Upvotes: 3

Related Questions