Php 扩展模型类导致找不到列错误
我正在使用 我创建了一个新类,它扩展了Php 扩展模型类导致找不到列错误,php,laravel,Php,Laravel,我正在使用 我创建了一个新类,它扩展了角色类。以下是角色的代码: <?php namespace Spatie\Permission\Models; use Illuminate\Database\Eloquent\Model; use Spatie\Permission\Traits\HasPermissions; use Spatie\Permission\Exceptions\RoleDoesNotExist; use Spatie\Permission\Contracts\Ro
角色
类。以下是角色的代码:
<?php
namespace Spatie\Permission\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Traits\HasPermissions;
use Spatie\Permission\Exceptions\RoleDoesNotExist;
use Spatie\Permission\Contracts\Role as RoleContract;
use Spatie\Permission\Traits\RefreshesPermissionCache;
class Role extends Model implements RoleContract
{
use HasPermissions;
use RefreshesPermissionCache;
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
public $guarded = ['id'];
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->setTable(config('laravel-permission.table_names.roles'));
}
/**
* A role may be given various permissions.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function permissions()
{
return $this->belongsToMany(
config('laravel-permission.models.permission'),
config('laravel-permission.table_names.role_has_permissions')
);
}
/**
* A role may be assigned to various users.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany(
config('auth.model') ?: config('auth.providers.users.model'),
config('laravel-permission.table_names.user_has_roles')
);
}
/**
* Find a role by its name.
*
* @param string $name
*
* @throws RoleDoesNotExist
*
* @return Role
*/
public static function findByName($name)
{
$role = static::where('name', $name)->first();
if (! $role) {
throw new RoleDoesNotExist();
}
return $role;
}
/**
* Determine if the user may perform the given permission.
*
* @param string|Permission $permission
*
* @return bool
*/
public function hasPermissionTo($permission)
{
if (is_string($permission)) {
$permission = app(Permission::class)->findByName($permission);
}
return $this->permissions->contains('id', $permission->id);
}
}
因此Role::create()
工作正常,但UserRole::create()
不行。将名称更改为Role
,然后将我的use子句更改为,因为SpatialRole
解决了这个问题。我猜这是与Eloquent有关的某种类型的类名关系问题。如果不在Eloquent模型上定义$table
属性,则表名将从模型名称派生。因此,默认情况下,Role
模型将使用roles
表。默认情况下,UserRole
模型将查找user\u roles
表
由于您仍然希望使用相同的表,但模型名称已更改,因此需要在新模型上定义$table
属性,使其查看角色
表
class UserRole extends Role
{
protected $table = 'roles';
// ...
}
我试过了。当它对主表起作用时,所有的关系表查询都被弄乱了,即使它们的表名在继承的模型中声明。@kjdion84是否发布了包配置文件并更改了model.role
键以指向自定义模型?
class UserRole extends Role
{
protected $table = 'roles';
// ...
}