提问者:小点点

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,'category_post_pad','post_id','pad_id');
}

类别型号:

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

}

pad型号:

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

}

后控制器

    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\u post\u padcategory\u idpost\u id0)值(3、104、2))

如何修复它?


共1个答案

匿名用户

尝试在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');
}