如何解决Laravel addGlobalScope 不明确的 id
我使用全局范围将我的用户模型划分为学生和教师。我的意思是我的学生和教师模型扩展了用户模型。 另外,我使用 UUID 而不是增量 ID。
这是我的用户模型类:
class User extends Authenticatable
{
use HasApiTokens,HasFactory,Notifiable,HasRoles;
protected $guard_name = 'web';
protected $fillable = [
'firstname','lastname','sex','mobile','password',];
protected $hidden = [
'password','remember_token','mobile_verified_at','updated_at','created_at'
];
protected $casts = [
'mobile_verified_at' => 'datetime',];
public function getRouteKeyName()
{
return 'id';
}
public function getIncrementing()
{
return false;
}
public function getKeyType()
{
return 'string';
}
public function academy()
{
return $this->belongsToMany(Academy::class);
}
}
这是我的学生模型课:
<?PHP
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Spatie\Permission\Traits\HasPermissions;
class Student extends User
{
protected static function booted()
{
static::addGlobalScope('students',function (Builder $builder) {
$builder->role('student')->join('users',function($join){
$join->on('students.id','=','users.id');
});
});
}
}
我的问题:
当我尝试使用 Student::firstOrCreate()
时,我会遇到此错误,例如:
sqlSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (sql: select * from `students` inner join `users` on `students`.`id` = `users`.`id` where (`id` = cd7873e5-f4e8-47dd-8d19-4b7bb73a90b3) and exists (select * from `roles` inner join `model_has_roles` on `roles`.`id` = `model_has_roles`.`role_id` where `students`.`id` = `model_has_roles`.`model_id` and `model_has_roles`.`model_type` = App\\Models\\Student and `roles`.`id` in (3d1e9c31-c7dd-4373-927c-9a2b4accca64)) limit 1)
而且 Student::Create()
没有问题!!
那么我该如何解决这个问题?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。