【问题标题】:Laravel 5.4 and up: Nothing posting to pivot tableLaravel 5.4 及更高版本:没有发布到数据透视表
【发布时间】:2017-10-07 20:08:42
【问题描述】:

我已经在 Stack 上搜索了 Laravel 文档和类似问题,但似乎找不到任何有用的东西。

我设置了一个名为 post_tag 的数据透视表,用于分别从 post 表和 tag 表中收集 post_id 和 tag_id - 但它们没有。数据完美地发布到 post 表和 tag 表,但 post_tag 表仍然为空。这是我的代码,我将永远感谢任何能够提供答案或至少为我指明正确方向的人,因为到目前为止我已经尝试了所有我能找到的东西。

只是为了确认一下,如果每个文件中的代码块与多对多关系无关,我会省略它们:

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

我还尝试在数据库中显式设置外键。当我在 Sequel Pro 中检查它们时,它们确实显示为外键,但是每当我发布新帖子时,我的 post_tag 表仍然显示为空。

我也尝试过使用 tinker 在 post_tag 表中手动附加 ID,这很有效 - 我从 Laracasts 上的 Laravel 5.4 基础视频系列中发现了这一点,但没有提到如何将它放入我的代码中,所以每当我发布新帖子时,它都会动态地将 post_id 和 tag_id 添加到数据透视表中。

感谢并期待您的帮助!

【问题讨论】:

  • 您正在创建帖子和标签,但没有迹象表明它们应该相关。 Laravel 不能假设它们应该是相关的,因为它们是在同一个函数中创建的。

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

您只需要附加您的模型。它看起来像:

$post = Post::create([

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

$tag = Tag::create([

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

阅读更多https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

【讨论】:

  • 非常感谢安德烈!一个多星期以来,我一直在尝试解决这个问题,而您在短短几分钟内就帮助解决了这个问题。
  • @SunilSandhu 没问题。只需阅读文档,一切都会好起来的
猜你喜欢
  • 1970-01-01
  • 2017-12-15
  • 2018-02-26
  • 2017-07-03
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
相关资源
最近更新 更多