首页 > 解决方案 > 如何将一个产品插入多个类别 laravel attach()

问题描述

我尝试了很多时间但失败了。例如:我想要的结果就像我将产品插入数据库并选择多个类别并将它们存储在不同的表中然后向我显示如下错误:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'space.category_product' doesn't exist (SQL: insert into `category_product` (`category_id`, `product_id`) values (1, ))

如果我手动将数据库表从 category_products 重命名为 category_product ,则在下面显示一个新错误:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_id' cannot be null (SQL: insert into `category_product` (`category_id`, `product_id`) values (1, ))

这是我的数据库代码

Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('model');
            $table->string('slug')->unique();
            $table->string('availability');
            $table->float('price');
            $table->longText('images');
            $table->text('short_detail');
            $table->text('feature');
            $table->longText('purchase_delivery');
            $table->longText('replace_policy');
            $table->timestamps();
        });
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('slug');
        $table->timestamps();
    });
    Schema::create('category_products', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('product_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');

        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        $table->timestamps();
    });

这是我的模型:

class Category extends Model
{
    public function Products()
    {
        return $this->belongsToMany(Product::class);
    }
}
class Product extends Model
{
    public function Categories()
    {
        return $this->belongsToMany(Category::class);
    }
}

产品控制器:

 public function store(Request $request)
    {
        if ($request->hasFile('file')){
            foreach ($request->file as $file) {
                $fileExt = $file->getClientOriginalExtension();
                $uniqId = uniqid('img-');
                $fileName[] =$uniqId.'.'.$fileExt;
                $Name = $uniqId.'.'.$fileExt;
                $file->move('public/uploads',$Name);
            }
            $images = implode(",",$fileName);
            $product = new Product();
            $product->Categories()->attach($request->categories_id);
            $product->name= $request->input('name');
            $product->model= $request->input('model');
            $product->slug= $request->input('slug');
            $product->availability= $request->input('availability');
            $product->price= $request->input('price');
            $product->images= $images;
            $product->short_detail= $request->input('short_detail');
            $product->feature= $request->input('feature');
            $product->purchase_delivery= $request->input('purchase_delivery');
            $product->replace_policy= $request->input('replace_policy');
            if ($product->save()) {
                return redirect()->route('product.index')
                    ->with('success', 'Product Added successfully');
            }
            return back()->withInput()->with('errors', 'Error Adding New Product');
        }
    }

标签: phplaraveldatabase-designeloquent

解决方案


在这里你可以使用你的模型

class Category extends Model
{
    public function Products()
    {
        return $this->belongsToMany(Product::class, 'category_products');
    }
}
class Product extends Model
{
    public function Categories()
    {
        return $this->belongsToMany(Category::class, 'category_products);
    }
}

category_products是一个数据透视表。

现在保存

$product = Product::create(['name' => 'product1']);
$product->Categories()->sync([1, 3, 4]);

或者

$product->Categories()->attach([1, 3, 4]);

区别

同步:您也可以使用同步方法来构建多对多关联。sync 方法接受要放置在中间表上的 ID 数组。任何不在给定数组中的 ID 都将从中间表中删除。因此,此操作完成后,中间表中将仅存在给定数组中的 ID:

附加:与附加相同,它将新值附加到现有值


推荐阅读