gpt4 book ai didi

php - Laravel 5.4 及以上版本 : Nothing posting to pivot table

转载 作者:太空宇宙 更新时间:2023-11-03 11:35:06 24 4
gpt4 key购买 nike

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

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

只是为了确认,如果每个文件与多对多关系无关,我已经从每个文件中省略了代码块:

Post.php

class Post extends Model
{

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

}

标签.php

class Tag extends Model
{

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

}

后 Controller .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 动态添加到数据透视表。

感谢并期待您的帮助!

最佳答案

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

$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

关于php - Laravel 5.4 及以上版本 : Nothing posting to pivot table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46624636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com