I have a 2 type of relationship between 2 models. Look at the code
protected $appends = [
'avatar_name'
];
public function avatar() {
return $this->hasOne(Avatar::class)->latest();
}
public function avatars()
{
return $this->hasMany('App\Models\Avatar');
}
public function getAvatarNameAttribute()
{
return $this->attributes['avatar_name'] = isset($this->avatar->name) ? $this->avatar->name : null;
}
Into Profile model I have only one relationship:
public function profile(){
return $this->belongsTo(Profile::class);
}
This relationships is clear for me - I need display all avatars for single profile (which he upload) and display one avatar which will be display in navigation or in a comments. Problem is that if I try to change the avatar, avatar_name displays all the time this same value. Profile models have avatar_id
field, of course.
@Update
I try check that in tinker, so I wrote
Profile::with('avatar')->find(1)->latest()->first()
But all the time it display this same avatar_name
My Answer:
>belongsTo('App\Models\Avatar');_}_public function getAvatarNameAttribute() {_ return $this->avatar->name;_}_In this code, I have a User model and an Avatar model with a belongsTo relationship between them. I have also defined an appends attribute in the User model to append the 'avatar_name' attribute.
The problem with this code is that the 'avatar_name' attribute will only be appended when the user model is loaded individually. If you try to load a collection of users, the 'avatar_name' attribute will not be appended to each user object.
To fix this issue, you can use the with() method when querying the users to eager load the avatar relationship and append the 'avatar_name' attribute to each user object. Here's an example:
php
$users = User::with('avatar')->get();
This will load all users along with their avatar relationship and append the 'avatar_name' attribute to each user object in the collection.
Rate this post
3 of 5 based on 1378 votesComments