php - 如何在laravel的产品表字段中插入具有3位唯一ID的类别名称
问题描述
在我的product
表中,我有一个product_id
字段不是primary key
我想category name
使用 laravel ORM 在该字段中插入 3 位唯一 ID 的字段。请帮助我如何实现它
类别表
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('description');
$table->timestamps();
});
产品表
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('product_id');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->string('name', 100);
$table->float('price', 5);
$table->text('description');
$table->timestamps();
});
产品存储方法
public function store(Request $request)
{
$product = new Product();
$product->product_id = **How can I implement that? (Example: Category-321)**
$product->name = $request->name;
$product->category_id = $request->category;
$product->price = $request->price;
$product->description= $request->description;
$product->save();
return redirect()->route('product.index');
}
解决方案
你可以使用mt_rand
像 -
public function store(Request $request)
{
$categoryname = $request->your-category-name;
do{
$productid = $categoryname.'-'.mt_rand(100, 999);;
}while(DB::table('products')->where('product_id', $productid)->exists());
$product = new Product();
$product->product_id = $productid;
$product->name = $request->name;
$product->category_id = $request->category;
$product->price = $request->price;
$product->description= $request->description;
$product->save();
return redirect()->route('product.index');
}
推荐阅读
- spring - 基于实体变量的 URL 块
- html - 无法在按钮内居中文本
- javascript - 使用 IntersectionObserver 在 React 中滚动时突出显示侧边栏导航项的问题
- excel - 使用 VBA 更新链接
- python - 安装了多个 Python 版本:如何为 CMD 和“打开方式”设置 py.exe(Windows 的 Python 启动器)的默认版本
- javascript - P5.js Safari iOS 滚动问题
- reactjs - preventDefault() 无法在 React 中提交
- windows - 在 Powershell 中,如何使用 CSV 中的行来搜索文本文件并将多行返回到另一个 CSV?
- css - CSS居中最后一行动态网格
- javascript - React Material Table pageSize 不会动态更新