属性 [users] 在此集合实例上不存在

Property [users] does not exist on this collection instance

此错误已在此处发布多次,但我遇到了一些不同的情况。我有两个名为 usersuser_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 one-to-one,我可以将此方法作为 属性 访问,但它向我显示了已定义的错误。我也试过将它作为一种方法来访问,但它说:

Method Illuminate\Database\Eloquent\Collection::users does not exist.

我也尝试通过 join() 获取它们,但它只返回了几个用户,我不知道为什么:

$users = Users::where('id', '>', '0')
        ->join('user_type', 'user_type.ut_id', '=', 'users.id')
        ->select([
            'user_type.ut_name',
            'users.*'
        ])->get();

谁能告诉我哪里做错了?

P.s:我只想显示所有用户各自的类型

在用户模型中

public function type(){
   return $this->hasOne(UserType::class, 'id');
}

在用户类型模型中

public function users(){
  return $this->belongsToMany(User::class, 'id');
}

你的关系好像有问题

用户链接到 ID 为 ut_id 的用户类型,但用户类型链接到 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();

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

首先,您定义了用户 table 的外键是 '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' 的用户 table 的外键,最初您在用户中将其命名为 'ut_id' table。在这个

/**
 * 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();

假设您的用户table有这种关系

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);
}