首页 文章

laravel eloquent不使用受保护的表名

提问于
浏览
1

在我的模型中,我添加了受保护的$ table,但是当我要使用它时,laravel不会使用它 . 这是我的榜样:

class Role extends Model
{
    protected $table = 'role';

    protected $primaryKey = 'ROLE_ID';

    protected $casts = [
        'ACTIVE' => 'boolean',
    ];

    protected $fillable = [
        'ROLE', 'ACTIVE', 'TYPE'
    ];

    public $timestamps = false;

    public function groups()
    {
        return $this->belongsToMany(Group::class, GroupRole::class, 'ROLE_ID', 'GROUP_ID');
    }
}

这是集团模型:

class Group extends Model
{
    protected $table = 'groups';

    protected $primaryKey = 'GROUP_ID';

    protected $fillable = [
        'GROUP_ID', 'GROUP_NAME', 'PARENT_GROUP', 'ACTIVE'
    ];

    protected $casts = [
        'ACTIVE' => 'boolean',
    ];

    public $timestamps = false;

    public function type()
    {
        return $this->belongsTo(GroupType::class, 'TYPE', 'TYPE_ID');
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, GroupRole::class, 'GROUP_ID', 'ROLE_ID');
    }
}

这是group_role表模型 . 它处理角色和组之间的多对多关系:

class GroupRole extends Model
{
    protected $table = 'group_role';

    protected $primaryKey = 'GROUP_ROLE_ID';

    protected $fillable = [
        'COMMENT', 'ROLE_ID', 'GROUP_ID'
    ];

    public $timestamps = false;
}

当我想使用这个模型时问题就开始了 . 例如:

$role = App\Role::first();
$groups = $role->groups;

Laravel返回此错误消息:

SQLSTATE [42S02]:未找到基表或视图:1146表'favian_mydb.App \ GroupRole'不存在(SQL:选择组 . *,App \ GroupRole.ROLE_ID为pivot_ROLE_ID,App \ GroupRole.GROUP_ID为pivot_GROUP_ID自组内部联接App.GroupRole on groups.GROUP_ID = App \ GroupRole.GROUP_ID其中App \ GroupRole.ROLE_ID = 1)

我试图用group_role替换App \ GroupRole并在mysql中执行 . 它工作正常 . 我错过了什么吗?

2 回答

  • 0

    问题出在您的 roles 关系中:

    public function roles()
    {
        return $this->belongsToMany(Role::class, GroupRole::class,'GROUP_ID','ROLE_ID');
    }
    

    belongsToMany 期望中间 table 名称作为第二个参数,而不是 class 名称 .

    所以你必须像这样定义它:

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'group_role','GROUP_ID','ROLE_ID');
    }
    
  • 1

    我认为问题在于你的关系功能 . 尝试使用字符串而不是Model :: class .

    例:

    return $this->return $this->belongsTo('App\GroupType', 'TYPE', 'TYPE_ID');

    希望这有效 .

相关问题