如何插入laravel数据透视表?

时间:2020-01-11 00:12:48

标签: mysql laravel laravel-5 eloquent

我有3张桌子:

stations (id,station_name) 
products (id,product_name)
product_station (station_id,product_id)

工作站型号

protected $fillable = ['station_name'];
public function products(){
        return $this->belongsToMany(Product::class);
    }

产品型号

 protected $fillable = ['product_name'];

public function stations(){
    return $this->belongsToMany(Station::class);
}

我已经插入了电台和产品,我想插入 将自己的产品用于数据透视表

AdminProductStation控制器

public function create()
    {
        $station = Station::pluck('station_name','id')->all();

        $products = Product::pluck('product_name','id')->all();

        return view('admin.product_stations.create',compact('station','products'));
    }

我认为下面的存储功能有误

    public function store(Request $request)
    {

        $station = new Station();

        $product = new Product();

        $station->save();

        $station->products()->attach($product);

        return redirect('/admin/product_stations');
     }

所以我遇到了这个错误

(2/2)QueryException SQLSTATE [23000]:违反完整性约束:1048列'product_id'不能为空(SQL:插入到product_stationproduct_idstation_id)值(,25)中)

4 个答案:

答案 0 :(得分:2)

"error": { "errors": [ { "message": "errorMessage", "locations": [ { "line": 1, "column": 11 } ], "extensions": { "code": "codeError", "dukar": 1000, } } ] } 期望相关Model的ID单一或数组,这意味着该Model应该事先创建。

您正在寻找的是attach()方法。

save(Model)

有关上述文档的更多信息,https://laravel.com/docs/5.8/eloquent-relationships#updating-many-to-many-relationships

答案 1 :(得分:1)

您应该先保存

$station = new Station();
$station->save();

$product = new Product();
$product->save();

然后 https://laravel.com/docs/6.x/eloquent-relationships#updating-many-to-many-relationships

$station->products()->attach($product->id);

OR

您可以尝试这样保存

$station->products()->save($product);

答案 2 :(得分:1)

// Post Model
public function categories()
    {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }
    public function tags()
    {
        return $this->belongsToMany('App\Tag')->withTimestamps();
    }

public function store(Request $request)
    {
        $this->validate($request,[
            'title' =>'required',
            'image' => 'mimes:jpeg,jpg,bmp,png',
            'categories' => 'required',
            'tags' => 'required',
            'body' => 'required',
            'live_demo' =>'required'
        ]);

          $image = $request->file('image');
        $slug = str_slug($request->title);
        if (isset($image))
        {
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
            $image_resize = Image::make($image->getRealPath());   
            $image_resize->resize(1600,1066);
            if (!file_exists('storage/uploads/post'))
            {
                mkdir('storage/uploads/post',0777,true);
            }
            //$image->move('storage/uploads/post',$imagename);
            $image_resize->save('storage/uploads/post/'.$imagename);
        }else{
            $imagename = "default.png";
        }

         $post = new Post();
        $post->user_id = Auth::id();
        $post->title = $request->title;
        $post->slug = str_slug($request->title);
        $post->image = $imagename;
        $post->body = $request->body;
        $post->price = $request->price;
        $post->live_demo = $request->live_demo;
        if(isset($request->status))
            {
                $post->status =true;
            }else
            {
                $post->status = false;
            }
        $post->is_approved = true;
        $post->save();
        $post->categories()->attach($request->categories);
        $post->tags()->attach($request->tags);

        Toastr::success('Post Successfully Save:)','Success');
        return redirect()->route('admin.post.index');
    }

// Pivot table create category_post column create   category_id, post_id.
// Pivot table create post_tag, and column create post_id, and tag_id

答案 3 :(得分:0)

  $station->products()->sync($request->products , false);