我正在嘗試在我的“用戶”、“個人資料”和“國家/地區”表之間建立關系。
- 用戶表包含以下列:id - name - email - password
- Profiles 表包含以下列:id - user_id - country_id
- 國家表有以下列:id - name - code
問題是目前我的代碼正在將用戶 ID 直接與國家表中的 ID 匹配(用戶一獲取國家一,用戶二 - 國家二等)。但是我想要做的是將組態檔表中的 country_id 與國家表中的國家 ID 匹配(因此用戶 1 的組態檔的 country_id 為 5,它在國家表中獲取 ID 為 5 的縣)。任何幫助糾正這一點都會非常感謝。
我的用戶模型
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable, Commenter;
public function country()
{
// if I remove 'id' I get the error "Unknown column 'countries.user_id'"
return $this->hasOne(Country::class, 'id');
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
我的個人資料模型
class Profile extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
public function country() {
return $this->belongsTo(Country::class);
}
}
我的國家模式
class Country extends Model
{
use HasFactory;
public function user()
{
return $this->hasMany(Profile::class);
}
}
我的用戶控制器
class UserController extends Controller
{
public function singleUserData($userId)
{
$singleUserData= User::where('id', $userId)->with('country','profile')->get();
return view('single-user-data', ['singleUserData' => $singleUserData]);
}
public function allUsersData() {
$allUsersData = User::with('profile','country')->get();
return view('all-users-data', ['allUsersData' => $allUsersData]);
}
}
uj5u.com熱心網友回復:
你們的關系有點不對勁。
您的個人資料模型是正確的 - 每個個人資料屬于一個國家并屬于一個用戶。
這是您的用戶和您的國家/地區模型不正確。您的用戶沒有“擁有一個”國家/地區,因為用戶和國家/地區之間沒有直接關系 - 它通過Profile 模型。因此,您正在尋找的是,您的用戶使用“ hasOneThrough ”關系來查找其國家/地區。
而且,反過來,每個國家/地區將(可能)擁有許多用戶,但不是直接的——再次通過 Profile 模型,因此您的國家/地區需要使用“ hasManyThrough ”關系來查找其用戶。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/331010.html
上一篇:如何從Laravel8中的回傳行解決此“未定義變數$last_number”
下一篇:Laravel7未定義的方法
