【问题标题】:how to insert one product to many categoies laravel attach()如何将一个产品插入多个类别 laravel attach()
【发布时间】:2018-12-06 07:07:12
【问题描述】:

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

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');
        }
    }

【问题讨论】:

    标签: php laravel database-design eloquent


    【解决方案1】:
      Schema::create('category_product', 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();
        });
    

    你的名字有错字,应该是category_product

    您的表名应按字母顺序排列并使用单数名称。

    如果您不想更改表名

     public function Categories()
        {
            return $this->belongsToMany(Category::class, 'category_products,'category_id', 'product_id');
        }
    

    我的产品控制器:

     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->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');
    
                $product->save();
                $product->Categories()->attach($request->categories_id);
    
                if ($product->save()) {
                    return redirect()->route('product.index')
                        ->with('success', 'Product Added successfully');
                }
                return back()->withInput()->with('errors', 'Error Adding New Product');
            }
        }
    

    $product->save()之后使用$product->categories()->attach($category_id)

    【讨论】:

    • 做到了,但它向我展示了这样的 SQLSTATE[23000]:完整性约束违规:1048 列'product_id'不能为空(SQL:插入category_productcategory_idproduct_id)值 (1, ))
    • @UzzalHosen 发布您尝试使用的代码attach
    • 这是我的代码$product->Categories()->attach($request->categories_id)
    • $product = new Product(); $product->Categories()->attach($request->categories_id);
    • @UzzalHosen 在 $product->save() 之后使用 $attach,因为当时还没有创建产品。
    【解决方案2】:

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

    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 将存在于 中间表:

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

    【讨论】:

    • [1, 3, 4] 是什么?
    • 这些是类别 ID
    • 我想存储两列$product->Categories()->attach(category_id,product_id);
    • 我要$product->Categories()->sync(category_id,product_id);
    • 是的,它会自动获取product_id。 $product->Categories()->attach([category_id])
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多