自加入问题:Laravel
Issue in self join : Laravel
数据库Table架构
if (!Schema::hasTable('tblrole')) {
Schema::create('tblrole', function (Blueprint $table) {
$table->unsignedInteger('RoleID')->autoIncrement();
$table->unsignedInteger('ParentRoleID')->nullable();
$table->string('Role', 25)->unique();
$table->boolean("IsActive")->default(0);
$table->foreign('ParentRoleID')->references('RoleID')->on('tblrole');
});
}
Eloquent型号
class RoleModel extends Model
{
public $table = 'tblrole';
public $primaryKey = 'RoleID';
public $timestamps = false;
protected $casts = [
'IsActive' => 'boolean'
];
public function ParentRole() {
return $this->hasOne("App\Models\User\Role\RoleModel", "RoleID", "ParentRoleID");
}
}
查询无效
$Roles = RoleModel
::select("RoleID", "Role", "IsActive")
->with(["ParentRole" => function($query) {
$query->select("RoleID", 'Role', "IsActive");
}])
->get();
工作查询[=34=]
$Roles = RoleModel->with("ParentRole")->get();
问题
在上面的无效查询中,ParentRole 始终为 null。
我错过了什么吗?
由于您明确地将 ParentRoleID
从查询中排除,eloquent 不知道它的值并且无法连接到父角色。尝试将 ParentRoleID
添加到您的 select()
或完全删除 select()
。
$Roles = RoleModel
::select("RoleID", "Role", "IsActive", "ParentRoleID")
->with(["ParentRole" => function($query) {
$query->select("RoleID", 'Role', "IsActive");
}])
->get();
数据库Table架构
if (!Schema::hasTable('tblrole')) {
Schema::create('tblrole', function (Blueprint $table) {
$table->unsignedInteger('RoleID')->autoIncrement();
$table->unsignedInteger('ParentRoleID')->nullable();
$table->string('Role', 25)->unique();
$table->boolean("IsActive")->default(0);
$table->foreign('ParentRoleID')->references('RoleID')->on('tblrole');
});
}
Eloquent型号
class RoleModel extends Model
{
public $table = 'tblrole';
public $primaryKey = 'RoleID';
public $timestamps = false;
protected $casts = [
'IsActive' => 'boolean'
];
public function ParentRole() {
return $this->hasOne("App\Models\User\Role\RoleModel", "RoleID", "ParentRoleID");
}
}
查询无效
$Roles = RoleModel
::select("RoleID", "Role", "IsActive")
->with(["ParentRole" => function($query) {
$query->select("RoleID", 'Role', "IsActive");
}])
->get();
工作查询[=34=]
$Roles = RoleModel->with("ParentRole")->get();
问题
在上面的无效查询中,ParentRole 始终为 null。
我错过了什么吗?
由于您明确地将 ParentRoleID
从查询中排除,eloquent 不知道它的值并且无法连接到父角色。尝试将 ParentRoleID
添加到您的 select()
或完全删除 select()
。
$Roles = RoleModel
::select("RoleID", "Role", "IsActive", "ParentRoleID")
->with(["ParentRole" => function($query) {
$query->select("RoleID", 'Role', "IsActive");
}])
->get();