Laravel 雄辩关系属于返回当前表而不是联接表



我正在尝试通过此代码处理此数据Auth::user()->personnel->currentAssignment->role->is_allowed但我是 getther null 值,因为假设角色值返回赋值,而不是角色数据。

到目前为止,这Auth::user()->personnel->currentAssignment工作正常,但是一旦我加入role,我就会获得PersonnelAssignment数据而不是RoleCatelog,这会导致null

请我是拉拉维尔的新手。我需要你的帮助。

如您所见,它返回以下数据:

"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 AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseQueryBuilder;
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 AppModels;
use IlluminateDatabaseEloquentModel;
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',
];

}

..

看到RoleCatalog模型上的主键是role_id我会尝试更改关系,如下所示:

class PersonnelAssignment extends Model
{    
public function role(){
return $this->belongsTo(RoleCatalog::class, 'role_id', 'role_id');
}
}
class RoleCatalog extends Model
{
public function personnelAssignment(){
return $this->hasMany(PersonnelAssignment::class, 'role_id', 'role_id');
}
}

顺便说一句,我会更改RoleCatalog模型的表名,现在它设置为相同的PersonnelAssignment表;两个模型都有protected $table = 'smed_personnel_assignment';

.

最新更新