代码之家  ›  专栏  ›  技术社区  ›  Sid Heart

如何在Laravel中附加多对多关系?

  •  2
  • Sid Heart  · 技术社区  · 8 年前

    我的桌子是这样做的

    产品表

    Schema::create('products', function (Blueprint $table) {
                $table->increments('id');
                $table->timestamps();
                $table->string('image');
                $table->string('stock');
                $table->string('title');
                $table->string('slug')->unique();
                $table->string('gender');
                $table->text('description');
                $table->integer('price');
                $table->integer('user_id')->unsigned();
                $table->foreign('user_id')->references('id')->on('users')
                            ->onDelete('restrict')
                            ->onUpdate('restrict');
    
                $table->dateTime('published_at');
            });
    

    和具有关系的颜色表

    Schema::create('colors', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name')->unique();
                $table->timestamps();
            });
    
            Schema::create('color_product', function (Blueprint $table) {
                $table->integer('color_id')->unsigned()->index();
                $table->foreign('color_id')->references('id')->on('colors')
                            ->onDelete('restrict')
                            ->onUpdate('restrict');
                $table->integer('product_id')->unsigned()->index();
                $table->foreign('product_id')->references('id')->on('products')
                            ->onDelete('restrict')
                            ->onUpdate('restrict');
                $table->timestamps();
            });
    

    我正试图在这样的一款产品中添加更多颜色

    public function addproductdetailspost(Request $request, $product){
    
            $product = product::where('slug', $product)->firstorfail();
            $color = color::where('name', $request->color)->firstOrCreate();
            $color->name = $request->color;
            $color->save();
            $product_id = $product->id;
            $color_id = $color->id;
            $product->colors()->attach($product_id);
            return Redirect::back()->with('status', 'Post Success');
        }
    

    它不起作用,我收到了这个错误

    Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::firstOrNew(), 0 passed in C:\xampp\htdocs\swimwear2\app\Http\Controllers\AdminController.php on line 109 and at least 1 expected
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Ohgodwhy    8 年前

    方向不对。

    $color->products()->attach($product_id);