如何在laravel中生成自定义的主ID? [英] how to generate custom primary id in laravel?
问题描述
我想在数据库中以类似的增量创建自定义主ID
- Comp-001
- Comp-002
- Comp-003
然后递增 Comp-00N
因为我相信您可以设置得更简单,并且根据您的描述,您只需要这种显示解决方案,所以我决定为您提出解决方案:>
公司型号
class Company extends Model
{
...
public function getCompanyID()
{
return sprintf('Comp-%03d', $this->id);
}
}
您的视图
在处理 Company 对象时,只需在需要显示它时调用您的方法即可:
$company->getCompanyID();
下面是一些有关其行为的示例:
ID示例和相应的输出:
IDs Outputs
1 Comp-001
45 Comp-045
104 Comp-104
1000 Comp-1000
这样,您将尊重:
-> Laravel自然流动;
->您保留真实的ID参考和视觉参考;
->您无需付出额外的努力来确保找到正确的产品(将ID保持为整数);
以上是解决问题的一种简单快捷的方法.
现在我不确定您如何构造代码,但是如果这是我的项目,我什至不更改Model并显示 Hydrator 或 Marshaller 要抓住我的对象,请仅在视图上使用我需要的字段创建类似的表示形式,然后将其传递.
为什么?
->我的模型尽可能纯,没有解析信息(实际上不应该是模型对OOP的责任);
->我在后端和前端之间有了清晰的转换,并且可以轻松地针对不同的视图进行更改,而无需触及先前的代码(尊重OOP的打开和关闭法则);
I want to create custom primary id in database with increment like
- Comp-001
- Comp-002
- Comp-003
and then increment Comp-00N
Because I believe you can set this simpler and from what you describe you only really need such solution for display, I decided to propose a solution for you:
Company Model
class Company extends Model
{
...
public function getCompanyID()
{
return sprintf('Comp-%03d', $this->id);
}
}
Your View
When handling the Company object, just call your method when you need to display it:
$company->getCompanyID();
Below are a few examples on how this will behave:
ID examples and respective outputs:
IDs Outputs
1 Comp-001
45 Comp-045
104 Comp-104
1000 Comp-1000
This way you will respect:
-> Laravel natural flow;
-> You keep a true ID reference and a visual reference;
-> You do not require extra effort to make sure you find the right product (you kept the ID as integer);
Above is a simple and quick solution to your problem.
Now I am not sure how you are structuring your code, but if it was my project I would even not change the Model and present either a Hydrator or a Marshaller to grab my object, create a similar representation with only the fields I required on the view and pass that instead.
Why?
-> My Model is a pure as possible with no parsing information (that really shouldn't be the Model responsability for OOP);
-> I get a clear transformation between Back-end and front-end and I can easily change for different views without having to touch previous code (respectful of open and closure laws of OOP);
这篇关于如何在laravel中生成自定义的主ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!