首页 > 解决方案 > 如何在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');
    }

标签: phplaraveleloquent

解决方案


你可以使用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');
}

推荐阅读