Reputation: 6078
I have a model called "Users", with the following information:
id
name
status_id
I have a model called "Status", with the following information:
id
description
When performing a raw query, one would naturally join the two tables on users.status_id = status.id
however I would like to use Laravel's Eloquent ORM to grab a user's status text.
eg. User::find(1)->status()->description
There are many different functions provided, such as has_one
, has_many
, and belongs_to
, but none of these work. Does anyone have any ideas on how I can do something like this?
Upvotes: 1
Views: 1338
Reputation: 14620
The way you have your database setup, you would add a has one user method to the Status model.
In your STATUS model:
public function user()
{
return $this->has_one('User');
}
This would let you query by status but not by user. To implement the functionality you want, ie User::find(1)->status()->description
you would need to have your database look like this
Users
id
name
Status
id
description
user_id
Now you would implement the following in your user model
public function status()
{
return $this->has_one('Status');
}
allowing you to use:
User::find(1)->status()->description;
This would allow you a one to one relationship between Users and Status. To implement a one to many relationship, i.e one user has many status' (probably not the best example) you can use the same database set up as above but instead in the user model you would have your user()
function return:
$this->has_many('Status');
Upvotes: 3
Reputation: 6078
I've found an answer. I can do the above by running a Fluent query instead of using a native relationship:
public function status() {
return Status::where('id', '=', $this->status_id)->first();
}
Upvotes: 1