samedi 18 avril 2020

Is there a way to have a custom attribute be the foreign key in a relationship in Laravel 5?

I have a xyz table that has a users first and last names in one column called user_name. I have a user's table where the first name and last name are separate columns. I need to to get the user from the user table when I query the xyz table. I want to make a custom attribute on the Users model and then use that in the relationship method on the xyz model. What I have now:

// XYZ model
public function user(){
    return $this->belongsTo('App\User', 'full_name');
}

Problem with this is that I get Column not found: 1054 Unknown column 'users.full_name' when running $xyzmodel->user()

On my user model i have:

protected $attributes = ['full_name'];
protected $appends = ['full_name'];

public function getFullNameAttribute()
{
    return "$this->first_name $this->last_name";
}

Anybody know how to accomplish this? Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire