Laravel 7:将枢轴附加到具有多个值的表

问题描述

我正在为3列创建数据透视表

我的数据透视表名称是:category_post_pad

category_id|  post_id | pad_id
-----------|----------|--------
 1         |        1 |      3
 1         |        4 |      1
 2         |        2 |      1

用户发送的每个帖子都包含一个类别和一个便笺本

帖子模型

public function categories()
{ 
 return $this->belongsToMany(Category::class,'category_post_pad','post_id','category_id');
}

public function pads()
{
return $this->belongsToMany(Pad::class,'pad_id');
}

类别模型:

public function posts()
{
    return $this->belongsToMany(Post::class,'category_id','post_id');

}

键盘型号:

public function posts()
{
    return $this->belongsToMany(Post::class,'pad_id','post_id');

}

PostsController

    public function store(Request $request)
{
    $data = $request->all();
    $post = Post::create($data);
    if ($post && $post instanceof Post) {
        $category = $request->input('categories');
        $pad = $request->input('pads');
        $post->categories()->attach([$category],[$pad]);
        return redirect()->back();
    }

}

但是告诉我这个错误

sqlSTATE [42S22]:找不到列:1054'字段列表'中的未知列'0'(sql:插入category_post_padcategory_idpost_id,{{1} })值(3,104,2))

如何修复?

解决方法

尝试使用以下代码作为PostsController中的存储功能:

$request->validate([
    'title' => 'required','body' => 'required','category_post_pad.*.category_id' => 'required|array|integer','category_post_pad.*.post_id' => 'required|array|integer','category_post_pad.*.pad_id' => 'required|array|integer',]);


$date = [
    'title' => $request->input('title'),'body' => $request->input('body'),];


$post = Post::create($date);

if ($post){
    if (count($request->input('category_id')) > 0){

        $date2 = array();

        foreach ( $request->input('category_id') as $key => $value ){
            $postCategory = array(
                'post_id'  => $post->id,'category_id'  => (int)$request->category_id[$key],'pad_id'    => (int)$request->pad_id[$key],);
            array_push($date2,$postCategory);
        }

        $post->categories()->attach($date2);
        return redirect()->back();
    }
}

然后,在您的Post模型内部更改类别关系:

public function categories()
{ 
    return $this->belongsToMany(Category::class,'category_post_pad','post_id','category_id')->withPivot('pad_id');
}