0
votes

I'm creating a pivot tables for 3 columns

my pivot table name is : category_post_pad

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

Each post sent by the user includes a category and an pad

Post Model

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

category model:

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

}

pad model:

public function posts()
{
    return $this->belongsToMany(Post::class,'category_post_pad','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();
    }

}

but show me this error

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into category_post_pad (category_id, post_id, 0) values (3, 104, 2))

how to fixit?

1

1 Answers

2
votes

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

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