[英]Laravel eloquent Has Many Through relationship
So, Here it is. 所以,就在这里。 I have 3 tables and the structure of them as follow: 我有3个表,它们的结构如下:
**user**
-id
-name
-password
-etc...
**user_general_info**
-id
-the_user_id
-country_id
-phone
-desc
...
**country**
-id
-name
For the obvious reason I have model for each 3 of them. 由于明显的原因,我为每个模型中的三个模型。 Now How do I declare eloquent relationship between these 3 so I can get data of user's country (something like $user->user_general_info->user_country->name
).? 现在如何声明这3个之间的雄辩关系,以便可以获取用户所在国家/地区的数据(例如$user->user_general_info->user_country->name
)。 I already tried a hasManyThrough
, but it didn't work out. 我已经尝试过一个hasManyThrough
,但是没有成功。
Do I have to add the country
foreign key to the user
table? 我是否必须将country
外键添加到user
表? Or am I missing something? 还是我错过了什么?
Thanks in advance. 提前致谢。
There are multiple ways to handle this. 有多种处理方法。 However, one of the cleanest method is by declaring a hasOne
relationship in your user model and retrieving the results. 但是,最干净的方法之一是在用户模型中声明hasOne
关系并检索结果。
So Suppose you have three models, User
, UserGeneralInfo
and Country
. 因此,假设您有三个模型, User
, UserGeneralInfo
和Country
。 Go to your User
model and declare the following. 转到您的User
模型并声明以下内容。
public function userGeneralInfo()
{
return $this->hasOne('App\UserGeneralInfo', 'user_id', 'id');
}
public function userCountry()
{
return $this->hasOne('App\Country', 'user_id', 'id');
}
Now when querying use the following 现在在查询时使用以下内容
$user = User:where('id, $id)->with('userGeneralInfo')->with('userCountry')->first();
This will give you the user along with its related general info and user country. 这将为您提供用户及其相关的一般信息和用户所在的国家/地区。 Now you can access the variables using. 现在,您可以使用来访问变量。
$user->userGeneralInfo->phone
to retrieve the phone number. $user->userGeneralInfo->phone
检索电话号码。 Similarly, $user-> userCountry->name
to get the country name. 同样,使用$user-> userCountry->name
获取国家/地区名称。
Note: There are multiple approaches to get your desired results, this one being and simplest amount them for starters to understand. 注意:有多种方法可以达到您想要的结果,这是最简单的方法,供初学者理解。 You can learn more about the complex relationships laravel relationships 您可以了解有关laravel关系的复杂关系的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.