【发布时间】:2021-11-21 17:07:02
【问题描述】:
PIVOT TABLE
| post_id | food_id | post_gram |
|:---- |:------: | -----: |
| 1 | 5 | NULL |
| 1 | 6 | NULL |
| 1 | 20 | NULL |
嗨,我有一个表 Post 和 Food 和数据透视表 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