Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Laravel Eloquent multiple relations to same table

I have the following table:

Table: rental_request
Columns:
id int(11) AI PK 
user_id int(11) 
address text 
number varchar(45) 
kvm varchar(45) 
rental varchar(45) 
zip varchar(45) 
city varchar(45) 
timestamp datetime 
created_at datetime 
updated_at datetime 
caseworker int(11)

Where user_id and caseworker points to my users table.

Now i am attempting to create this relationship in my Laravel application:

    class rental_request extends Model
{
    protected $table = 'rental_request';
    protected $fillable = ['user_id','address', 'number', 'kvm','rental','zip','city', 'caseworker'];

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

    public function caseworker()
    {
        return $this->hasOne('App\User', 'user_id', 'caseworker');
    }
}

In my controller I collect the data from the table using:

rental_request::orderBy('id', 'desc')->get();

Now, this actually works but only for the user and not for the caseworker.

Which means I have a user object on my result but not a caseworker object.

Can anyone tell me what I've done wrong?

Upvotes: 3

Views: 2336

Answers (2)

Marvin Collins
Marvin Collins

Reputation: 379

you can use with to get caseworker

rental_request::with(['caseworker','user'])->orderBy('id', 'desc')->get();

Upvotes: 3

patricus
patricus

Reputation: 62248

Your caseworker relationship should also be defined as a belongsTo relationship. The rental_request model has the foreign key, so it belongs to the foreign model.

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

Upvotes: 2

Related Questions