简体   繁体   中英

Laravel 5.4 and up: Nothing posting to pivot table

I've scoured the Laravel docs and similar questions here on Stack but can't seem to find anything that works.

I have a pivot table set up called post_tag, which is meant to gather the post_id and the tag_id from the post table and tag table, respectively - but they don't. Data posts to the post table and to the tag table perfectly, but the post_tag table remains empty. Here is my code, I will be forever indebted to anyone who is able to provide an answer, or at least point me in the right direction, as I've tried everything I can find thus far.

Just to confirm, I've omitted chunks of code from each file if they're not relevant to the many-to-many relationship:

Post.php

class Post extends Model
{

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

}

Tag.php

class Tag extends Model
{

public function posts()
{
    return $this->belongsToMany(Post::class);
}

}

PostController.php

    public function store(Request $request)
{
    $this->validate(request(), [

        'content' => 'required',
        'tag' => 'required'
    ]);

    Post::create([

        'content' => request('content'),
        'user_id' => auth()->id()
    ]);

    Tag::create([

        'tag' => request('tag'),
    ]);

    return redirect('/');

}

create_post_tag_table.php

class CreatePostTagTable extends Migration
{
public function up()
{
    Schema::create('post_tag', function (Blueprint $table) {


        $table->integer('post_id');
        $table->integer('tag_id');
        $table->primary(['post_id', 'tag_id']);
    });
}

I've also tried explicitly setting up foreign keys in the database. These did indeed show up as foreign keys when I checked them in Sequel Pro, but my post_tag table was still showing up as empty whenever I made new posts.

I've also tried using tinker to manually attach IDs in the post_tag table which worked - I found out about this from the Laravel 5.4 fundamentals video series on Laracasts, but there was no mention of how to put this into my code so that it would dynamically add the post_id and the tag_id to the pivot table whenever I make a new post.

Thanks and look forward to your help!

You just need to attach your models. It looks like:

$post = Post::create([

    'content' => request('content'),
    'user_id' => auth()->id()
]);

$tag = Tag::create([

    'tag' => request('tag'),
]);
$post->tags()->attach($tag->id);

Read more https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM