首页 > 解决方案 > 此集合实例上不存在属性 [用户]

问题描述

此错误已在此处多次发布,但我遇到的情况有些不同。我有两个名为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:我只想向所有用户展示他们各自的类型

标签: phplaraveleloquentormlaravel-6

解决方案


您错过了用户表和用户类型表之间的确切外键。

首先,您定义了用户表的外键是“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);
}

推荐阅读