英文:
Implementing nextval(); sequence in Laravel
问题
我要翻译的内容如下:
Route::get('/check-student-id', function() {
$prefix = "20";
$lastId = max(StudentModel::max('Student ID'), PersonModel::max('id'));
$suffix = str_pad(($lastId % 100000) + 1, 5, '0', STR_PAD_LEFT);
$newId = $prefix . $suffix;
$existingIds = array_merge(
StudentModel::pluck('Student ID')->toArray(),
PersonModel::pluck('id')->toArray()
);
while (in_array($newId, $existingIds)) {
$suffix = str_pad(($suffix % 100000) + 1, 5, '0', STR_PAD_LEFT);
$newId = $prefix . $suffix;
}
return $newId;
});
你可以在 Laravel 项目中实现 PostgreSQL 的 nextval()
函数,但上面的代码并没有包含 nextval()
的实现。如果你需要帮助添加 nextval()
的逻辑,请提供更多细节以便我帮助你进一步。
英文:
How can I implement the nextval();
function from PostgreSQL to my ID generator in my Laravel project?
I've tried the suggestion from ChatGPT but it does not work, I also searched the documentation about nextval
but cant still get it to work in my project.
This is my function that generates the ID, the rule of my id generation is that it will scan the Student ID and id column of the StudentModel
and PersonModel
before generating an unassigned id, then the id will start with the prefix of 20 and must only be a 7 digit long. I have no problem generating ID numbers, but I want to implement the nextval()
in my function.
Route::get('/check-student-id', function() {
$prefix = "20";
$lastId = max(StudentModel::max('Student ID'), PersonModel::max('id'));
$suffix = str_pad(($lastId % 100000) + 1, 5, '0', STR_PAD_LEFT);
$newId = $prefix . $suffix;
$existingIds = array_merge(
StudentModel::pluck('Student ID')->toArray(),
PersonModel::pluck('id')->toArray()
);
while (in_array($newId, $existingIds)) {
$suffix = str_pad(($suffix % 100000) + 1, 5, '0', STR_PAD_LEFT);
$newId = $prefix . $suffix;
}
return $newId;
});
</details>
# 答案1
**得分**: 1
`nextval` 用于获取 SEQUENCE 的下一个值。你的问题与此无关。你只需要为你的 id 字段设置默认值。
这可以通过在模型创建时更新字段来实现
```php
class YourModel extends Model
{
public static function booted()
{
static::creating(function ($model) {
... 在这里编写逻辑
$model->id = $newId;
});
}
}
这仅在使用 Eloquent 持久化数据时有效。
如果你希望表格无论如何持久化数据都能自动获得这个值,那么你需要在数据库中实现这个逻辑。
英文:
nextval
is used to obtain the next value of a SEQUENCE. What you're asking doesn't have anything to do with that. You just want to give a default value to your id field.
This can be achieved by updating the field when a model is created
class YourModel extends Model
{
public static function booted()
{
static::creating(function ($model) {
... logic here
$model->id = $newId;
});
}
}
This is limited to only working when Eloquent is used to persist the data.
If you want the table to get this value automatically no matter how you persist the data, then you'll need to implement that logic in the database
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论