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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With