Debiprasad
Debiprasad

Reputation: 6153

Eloquent Model Many to One Relationship

Take this example:

I have a table users with fields as id, name, city. I have another table, which contains name of the cities. The table name is cities and fields are: id, name. So, I store the id (primary key) of a city in the city column of the table users. While getting an user Eloquent model, what is the best way to get the name of the city?

Upvotes: 0

Views: 630

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81147

By convention you would name your relation city(), but there is also an attribute city being foreign key, so you can't access the related model.

If so, then I suggest renaming the foreign key to city_id or something like that, then it will work:

$user->city; // City model
$user->city->name;

Otherwise, if you can't change the schema, then rename relationship:

// User model
public funciton relatedCity()
{
  return $this->belongsTo('City', 'city');
}

// then
$user->relatedCity->name;

Upvotes: 1

Ali
Ali

Reputation: 151

Assuming that you have already configured the Models

// find a user named John
$user = User::where('name', '=', 'John')->first();

// get the city of the user
$userCity = $user->city;

Upvotes: 0

Related Questions