简体   繁体   English

雄辩的模型多对一关系

[英]Eloquent Model Many to One Relationship

Take this example: 举个例子:

I have a table users with fields as id , name , city . 我有一个表users ,其字段为idnamecity I have another table, which contains name of the cities. 我有另一个表,其中包含城市名称。 The table name is cities and fields are: id , name . 表名称是cities ,字段是: idname So, I store the id (primary key) of a city in the city column of the table users . 因此,我将城市的ID(主键)存储在表userscity列中。 While getting an user Eloquent model, what is the best way to get the name of the city? 在获得用户口才模型的同时,获得城市名称的最佳方法是什么?

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. 按照约定,您将命名您的关系city() ,但是还有一个属性city是外键,因此您无法访问相关模型。

If so, then I suggest renaming the foreign key to city_id or something like that, then it will work: 如果是这样,那么我建议将外键重命名为city_id或类似的名称,那么它将起作用:

$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;

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM