[英]Laravel eloquent Has Many Through relationship
所以,就在這里。 我有3個表,它們的結構如下:
**user**
-id
-name
-password
-etc...
**user_general_info**
-id
-the_user_id
-country_id
-phone
-desc
...
**country**
-id
-name
由於明顯的原因,我為每個模型中的三個模型。 現在如何聲明這3個之間的雄辯關系,以便可以獲取用戶所在國家/地區的數據(例如$user->user_general_info->user_country->name
)。 我已經嘗試過一個hasManyThrough
,但是沒有成功。
我是否必須將country
外鍵添加到user
表? 還是我錯過了什么?
提前致謝。
有多種處理方法。 但是,最干凈的方法之一是在用戶模型中聲明hasOne
關系並檢索結果。
因此,假設您有三個模型, User
, UserGeneralInfo
和Country
。 轉到您的User
模型並聲明以下內容。
public function userGeneralInfo()
{
return $this->hasOne('App\UserGeneralInfo', 'user_id', 'id');
}
public function userCountry()
{
return $this->hasOne('App\Country', 'user_id', 'id');
}
現在在查詢時使用以下內容
$user = User:where('id, $id)->with('userGeneralInfo')->with('userCountry')->first();
這將為您提供用戶及其相關的一般信息和用戶所在的國家/地區。 現在,您可以使用來訪問變量。
$user->userGeneralInfo->phone
檢索電話號碼。 同樣,使用$user-> userCountry->name
獲取國家/地區名稱。
注意:有多種方法可以達到您想要的結果,這是最簡單的方法,供初學者理解。 您可以了解有關laravel關系的復雜關系的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.