提问人:devsead 提问时间:11/17/2023 最后编辑:matiaslauritidevsead 更新时间:11/19/2023 访问量:36
Laravel 10 中的 getKeyName 在 slug 是主键时导致测试中出现问题
getKeyName in Laravel 10 causes issue in test when slug is primary key
问:
我一直在研究 rest api,现在我正在做一些测试,但由于我想在我的模型上使用 slug 作为主键(通常使用 getKeyName 设置),我有奇怪的行为。例如,对于此 create 方法:
$modelInstance = Model::create([
'title' => 'Old Title',
'slug' => Str::slug('Old Title'),
'description' => 'Old description',
'rating' => 4.2,
]);
我在转储测试时得到这些结果:
#original: array:6 [
"title" => "Old Title"
"slug" => 9
"description" => "Old description"
"rating" => 4.2
"updated_at" => "2023-11-17 08:45:08"
"created_at" => "2023-11-17 08:45:08"
]
#changes: []
#casts: []
#classCastCache: []
#attributeCastCache: []
然后当我评论这个时:
public function getKeyName(): string
{
return 'slug';
}
在我的模型中的一部分并运行相同的测试,我得到这个:
#original: array:7 [
"title" => "Old Title"
"slug" => "old-title"
"description" => "Old description"
"rating" => 4.2
"updated_at" => "2023-11-17 08:47:31"
"created_at" => "2023-11-17 08:47:31"
"id" => 9
]
#changes: []
我最近没有经常使用 Laravel 10,但是我是否缺少一些我应该注意的东西?
答:
0赞
Denis Sinyukov
11/17/2023
#1
尝试根据需要设置所有值 PHP
class Model {
public $incrementing = false;
protected $primaryKey = 'slug';
protected $keyType = 'string';
}
因此,现在在 CRUD 结果时将不使用 id 字段。所有的焦点都集中在蛞蝓领域。
incrementing
- 说没有必要自己加primaryKey
- getKeyName() 返回其值,并说这现在是主字段。keyType
- 用于 Builder 中的 where 查询等。
评论
$incrementing
performInsert()
auto incrementing
php class Model { public $incrementing = false; protected $primaryKey = 'slug'; protected $keyType = 'string';
id
slug
incrementing
primaryKey
keyType