php - 此集合实例上不存在属性 [用户]
问题描述
此错误已在此处多次发布,但我遇到的情况有些不同。我有两个名为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:我只想向所有用户展示他们各自的类型
解决方案
您错过了用户表和用户类型表之间的确切外键。
首先,您定义了用户表的外键是“ut_id”基础,基于您的 belongsTo 关系。在这个
/**
* 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);
}
推荐阅读
- python - 如何在python中使用JSON数据分配变量
- python - 检查 USB 是否可用并使用 python 检查 mp3 和 mp4 文件
- docker - 容器变换给出缺少图像参数错误
- python - 如何使用 NSGA-II(在 python/pymoo 库中)从列表中选择最佳值对
- prolog - Setof:有没有办法提前停止?
- python - 如何对变量执行数学运算到烧瓶模板中
- ruby-on-rails - rails: nil:NilClass 的未定义方法`>'
- javascript - Highcharts - 对数图表 - Y 轴网格线显示在图表中间,用于范围窄的数据集
- php - Composer 安装不兼容的包
- flutter - 有没有办法根据 Flutter 中的可用空间自动调整 Table 小部件的行高?