当通过Eloquent创建一个新模型时,如下所示:
$appUser = AppUser::create([
'id' => Str::uuid(),
'name' => $request->name,
'location' => new Point(rand(0,90), rand(0,180))
]);
在同一个请求中,我像这样访问对象...:
$location = $appUser->location;
$name = $appUser->name; //I can get this from the request, but I have lots of random fields generated for test users and it's much more convenient if I could just access the created properties, including the default ones.
...然后,有时,属性是空的(当这种情况发生时,所有属性都是空的,id是0
)。这就像数据库在以这种方式访问之前没有足够的时间来创建对象。
我尝试在访问属性之前发出refresh()
,但是这个$appUser->refresh()
有时会抛出以下错误:
Unknown error: No query results for model [App\Models\AppUser]
这也指出了对象还没有持久化的方向。但是如果对象没有持久化,为什么PHP线程会继续执行(MariaDB 5.6,PHP 7.4)?
编辑:AppUser模型:
class AppUser extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'name',
'location'
];
protected $casts = [
'id' => 'string'
];
}
模式:
Schema::create('app_users', function (Blueprint $table) {
$table->uuid('id')->primary()->unique();
$table->timestamps();
$table->boolean('active')->default(true);
$table->string('name', 128);
$table->geometry('location')->nullable();
});
1条答案
按热度按时间l0oc07j21#
我认为您的模型仍然在数据库中寻找
ID
(整数)的自动递增值,但您在那里有一个UUID
。Eloquent还将假设每个模型对应的数据库表都有一个名为id的主键列。如果需要,您可以在模型上定义一个受保护的$primaryKey属性,以指定一个不同的列作为模型的主键。此外,Eloquent假设主键是一个递增的整数值,这意味着Eloquent将自动将主键转换为整数。
为了使用
UUID
作为主键,必须向模型添加两个属性:你可以在这里找到更多关于递增和键类型的信息。