Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: belongsTo not working when changing it's function name

I have this relation Artist - has many - Album

Artist class:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Artist extends Model {

  public function albums()
  {
    return $this->hasMany('App\Album');
  }

}

Album class:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Album extends Model {

  public function artist()
  {
    return $this->belongsTo('App/Artist');
  }

}

If I do this: $album->artist there's no problem at all

But if I change the function's name inside Album class without changing the model/class name:

public function artistInfo()
{
  return $this->belongsTo('App\Artist');
}

Then, this won't work: $album->artistInfo. It returns null for me

P.S. This is not my real schema but the problem only appears when I change the function's name of the belongsTo.

like image 962
Mathius17 Avatar asked Feb 10 '23 11:02

Mathius17


1 Answers

Well, I found the proper answer and it turns out that it's an easy one.

In the relationship function specify the keys (foreign key and local key). For this example:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Album extends Model {

  public function artistInfo()
  {
    return $this->belongsTo('App/Artist','artist_id','id');
  }

}

Now you can do it as usual: $artist->artistInfo or Album::find(1)->artistInfo->name

like image 138
Mathius17 Avatar answered Feb 13 '23 02:02

Mathius17