本文介绍了Laravel 7:将枢轴附加到具有多个值的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a pivot tables for 3 columns

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

my pivot table name is : 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');

}

垫子型号:

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

}

PostsController

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();
    }

}

但是告诉我这个错误

如何修复?

推荐答案

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

Try using the following code as the store function in your 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模型内部更改您的类别关系:

Then, inside of your Post model change your catagory relation:

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

这篇关于Laravel 7:将枢轴附加到具有多个值的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 21:16