【问题标题】:Laravel add multiple data to pivot tableLaravel 向数据透视表添加多个数据
【发布时间】:2021-11-21 17:07:02
【问题描述】:

PIVOT TABLE

| post_id | food_id | post_gram |
|:----    |:------: | -----:    |
| 1       | 5       | NULL      |
| 1       | 6       | NULL      |
| 1       | 20      | NULL      |

嗨,我有一个表 PostFood 和数据透视表 food_post,当我想将数据保存到它保存的数据透视表时只有 post id 和 food id 但 post_gram 没有(它将值设置为 NULL).. 在 blade 我有选择输入来选择食物 select=name"select2[]" 和输入写多少克select=name"select3[]",然后是一个复制它的按钮,以便用户可以添加他想要多少食物,我需要将数据保存到数据透视表中克的值被保存并且db中没有空值,在模型中我定义“withPivot”我也尝试了attach()并且它抛出错误说“数组到字符串转换”

---------------**BLADE** ----------------
<div class="flex my-5" id="duplicater">

       <select name="select2[]"  id="select">
           <option disabled selected>Vyberte prosím potravinu</option>
           @foreach ($food as $f )
           <option value="{{$f->id}}">{{$f->nazev}}</option>
           @endforeach
       </select>

       <div>
           <input id="food" type="text" name="select3[]" value="" placeholder="Počet gramů">
       </div>
   </div>

   </div>

<button type="submit" class="uppercase mt-15 bg-gray-900 text-gray-100 text-lg font-bold py-4 px-20 rounded-2xl ">Submit Post</button>
</form>
<button id="button" class="p-3 my-6 border-green-400 border text-green-400" onclick="duplicate()">Přidat další potravinu</button> 
--------------**Post Controller**----------------

public function store(Request $request)
   {
       //dd($request->select2);
       $data = [];

       $request->validate([
           'title' => 'required',
           'description' => 'required',
           'image' => 'required|mimes:jpg,png,jpeg|max:5048'
       ]);

       $newImageName = uniqid() . '-' . $request->title . '.' . $request->image->extension();

       $request->image->move(public_path('images'), $newImageName);



       $post = new Post();
       $post->title = $request->input('title');
       $post->description = $request->input('description');
       $post->slug = SlugService::createSlug(Post::class, 'slug', $request->title);
       $post->image_path =$newImageName;
       $post->user_id = auth()->user()->id;

       $post->save();
         

-----------------------------------------------------------------------------
         -----------here is the attach to the pivot table -------------
-----------------------------------------------------------------------------
           $post->food()->sync($request->select2,[
       'post_gram' => $request->select3
           ]);


       return redirect('/blog')
           ->with('message', 'Your post has been added!');
   }

--------------后模型-------------------- --------

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
use Laravelista\Comments\Commentable;

class Post extends Model
{
   use HasFactory;
   use Sluggable;
   use Commentable;


       protected $fillable = ['title','slug' ,'description' , 'image_path', 'user_id'];

   public function user(){
           return $this->belongsTo(User::class);
   }
   public function food(){
       return $this->belongsToMany(Food::class)->withPivot('post_gram');//->withPivot(['post_kalorie','post_bilkoviny','post_sacharidy','post_tuky','post_objem']);
   }
   public function sluggable():array{
       return[
           'slug'=>[
               'source' => 'title'
           ]
       ];
   }
}

【问题讨论】:

  • 您也需要在控制器和模型中将post_objem 更改为post_gram

标签: php laravel pivot


【解决方案1】:

列名是post_gram

在模型中

改变

public function food(){
   return $this->belongsToMany(Food::class)->withPivot('post_objem');
}

public function food(){
   return $this->belongsToMany(Food::class)->withPivot('post_gram');
}

在控制器中

如下使用sync 助手

$post->food()->sync([$request->select2,$request->select3]);

如下使用attach 助手

$post->food()->attach([$request->select2,$request->select3]);

【讨论】:

  • 嗨,我将模型和控制器更改为 post_gram,但仍然没有 ://
  • 你能展示数据透视表的模型吗?
  • &lt;?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class FoodPost extends Model { use HasFactory; }
  • 根据我编辑的答案使用sync helper。请检查
  • 我试了一下,但它抛出错误`SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into food_post (food_id, post_id, 0) 值 (0, 55, 9)) `
猜你喜欢
  • 1970-01-01
  • 2018-02-08
  • 2013-07-02
  • 2019-06-12
  • 2014-10-31
  • 1970-01-01
  • 2016-01-23
  • 2018-04-10
  • 2018-11-14
相关资源
最近更新 更多