[英]Property [users] does not exist on this collection instance
此錯誤已在此處發布多次,但我遇到了一些不同的情況。 我有兩個名為users
和user_type
表。 users
使用來自user_type
的外鍵。 我必須獲取所有用戶及其類型,我使用 Laravel 的 Eloquent ORM 來定義關系,這是一對一的關系。
用戶型號:
/**
* Get the user type that user has.
*/
public function users(){
return $this->belongsTo('App\Models\UserType', 'ut_id', 'id');
}
用戶類型模型:
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'ut_id';
/**
* Get the user associated with the user type.
*/
public function users(){
return $this->hasOne('App\Models\Users', 'user_type_id', $this->primaryKey);
}
獲取控制器:
$users = Users::all()->users;
根據Laravel ORM 一對一,我可以將此方法作為屬性訪問,但它向我顯示了定義的錯誤。 我也嘗試將它作為一種方法訪問,但它說:
方法 Illuminate\\Database\\Eloquent\\Collection::users 不存在。
我也嘗試通過join()
獲取它們,但它只返回少數用戶,我不知道為什么:
$users = Users::where('id', '>', '0')
->join('user_type', 'user_type.ut_id', '=', 'users.id')
->select([
'user_type.ut_name',
'users.*'
])->get();
有人能告訴我我做錯了什么嗎?
Ps :我只想顯示所有用戶各自的類型
您錯過了用戶表和用戶類型表之間的確切外鍵。
首先,您定義了用戶表的外鍵是您的belongsTo 關系中的“ut_id”基礎。 在這一
/**
* Get the user type that user has.
*/
public function users(){
return $this->belongsTo('App\Models\UserType', 'ut_id', 'id');
}
其次,在您的用戶類型模型中,您使用了名為“user_type_id”的用戶表的外鍵,最初您在用戶表中將其命名為“ut_id”。 在這一
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'ut_id';
/**
* Get the user associated with the user type.
*/
public function users(){
return $this->hasOne('App\Models\Users', 'user_type_id', $primaryKey);
}
您必須匹配用於解決問題的外鍵。
現在,要獲取所有用戶的類型,您的查詢應如下所示。
$users = Users::with('users')->get();
假設您的用戶表具有這種關系
public function users(){
return $this->belongsTo('App\Models\UserType', 'ut_id', 'id');
}
並且您的用戶類型模型具有這種關系
public function users(){
return $this->hasOne('App\Models\Users', 'ut_id', $this->primaryKey);
}
在用戶模型中
public function type(){
return $this->hasOne(UserType::class, 'id');
}
在用戶類型模型中
public function users(){
return $this->belongsToMany(User::class, 'id');
}
你們的關系似乎不對。
用戶鏈接到 id 為 ut_id 的 UserType,但 userType 鏈接到 id 為 user_type_id 的用戶
我很確定它應該是 userTypes
/**
* Get the user associated with the user type.
*/
public function users(){
return $this->hasMany('App\Models\Users', 'id', 'user_type_id');
}
然后這對於用戶
public function userTypes(){
return $this->belongsTo('App\Models\UserType', 'user_type_id', 'id');
}
然后你可以急切地加載你想要的所有結果......
$users = Users::where('id', '>', '0')
->with('userTypes')
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.