【发布时间】: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