【发布时间】:2026-02-16 05:40:01
【问题描述】:
我正在尝试通过此代码获取此数据
Auth::user()->personnel->currentAssignment->role->is_allowed
但我是空值,因为假设角色值返回分配,而不是角色数据。
到目前为止Auth::user()->personnel->currentAssignment 工作正常,但是一旦我加入role,我得到PersonnelAssignment 数据而不是RoleCatelog 这导致null 值
请我是 Laravel 的新手。我需要你的帮助。
如您所见,它返回了以下数据:
"current_assignment": {
"id": "778",
"personnel_id": "100751",
"area_id": 154,
"role_id": 17,
"dept_id": 154,
"start_date": "2017-11-08",
"end_date": null,
"is_temporary": null,
"is_deleted": null,
"modify_id": "Sample Name",
"modify_dt": null,
"create_id": "Administrator",
"create_dt": null,
"transfer_id": null,
"transfer_dt": null,
"role": {
"id": "101",
"personnel_id": null,
"area_id": 154,
"role_id": 17,
"dept_id": 154,
"start_date": "2007-05-04",
"end_date": null,
"is_temporary": null,
"is_deleted": null,
"modify_id": "Sample Name II",
"modify_dt": null,
"create_id": "Sample Name II",
"create_dt": null,
"transfer_id": null,
"transfer_dt": null
}
}
这用于分配模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
class PersonnelAssignment extends Model
{
protected $table = 'smed_personnel_assignment';
protected $primaryKey = 'id';
protected $keyType = 'string';
public $incrementing = false;
public $timestamps = false;
protected $fillable = [
'id',
'personnel_id',
'area_id',
'role_id',
'dept_id',
'start_date',
'end_date',
'modify_id',
'modify_dt',
'create_id',
'create_dt',
];
public function role(){
return $this->belongsTo(RoleCatalog::class, 'role_id');
}
}
这是为了榜样......
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class RoleCatalog extends Model
{
protected $table = 'smed_personnel_assignment';
protected $primaryKey = 'role_id';
public $incrementing = false;
public $timestamps = false;
protected $fillable = [
'role_id',
'role_name',
'role_desc',
'role_area',
'is_allowed',
'is_deleted',
'modify_id',
'modify_dt',
'create_id',
'create_dt',
];
}
..
【问题讨论】:
-
您应该尝试发布Minimal Reproducible Example,如果您对最后两个模型有问题:
currentAssignment->role->is_allowed,最好只发布这两个模型和重现问题的最少代码。我们同意Auth::user()->personnel->currentAssignment工作正常吗?并非这里的每个人都有空闲时间阅读所有这些代码,您可能无法得到一个好的答案。 -
RoleCatalog类中是否有方法is_allowed?您能否还显示RoleCatalog的迁移文件? -
@Adam 我现在没有使用迁移,因为我还不熟悉如何去做。是的,有
is_allowed,我也发布了 RoleCatalog 模型。但我是从作业中获取数据。我在这种情况下使用 belongsTo 错了吗? -
@dparoli 我已经更新了我的帖子,感谢您的提示。
标签: laravel eloquent laravel-5.8 php-7.2 eloquent-relationship