自我加入问题:Laravel

时间:2017-06-28 02:18:42

标签: laravel laravel-5.3 laravel-5.4

数据库表架构

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

    });
}

雄辩模型

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

工作查询

$Roles = RoleModel->with("ParentRole")->get();

问题

在上面的不工作查询中,ParentRole始终为null。

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

由于您明确地从查询中排除了ParentRoleID,因此eloquent不知道其值,也无法建立与父角色的连接。尝试将ParentRoleID添加到select()或完全删除select()

$Roles = RoleModel
::select("RoleID", "Role", "IsActive", "ParentRoleID")
->with(["ParentRole" => function($query) {
    $query->select("RoleID", 'Role', "IsActive");
}])
->get();