【发布时间】:2023-01-09 18:11:55
【问题描述】:
我有这些:
帖子表
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title', 64);
$table->string('teaser', 128)->nullable();
$table->text('content', 50000);
$table->timestamps();
});
}
职位模型
use HasFactory;
protected $fillable = ['title', 'teaser', 'content'];
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
}
标签表
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('text', 32);
});
}
标签模型
use HasFactory;
public $timestamps = false;
public $fillable = ['text'];
public function posts()
{
return $this->belongsToMany(Post::class, 'post_tag', 'tag_id', 'post_id');
}
post_tag 表
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('post_id');
$table->unsignedInteger('tag_id');
});
}
当我尝试创建带有标签的新帖子时,出现此错误:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'test' for column `laravel`.`post_tag`.`tag_id` at row 1
INSERT INTO
`post_tag` (`post_id`, `tag_id`)
VALUES
(31, test)
这就是我正在尝试的方式:
public function store(PostFormValidation $request)
{
$newpost = Post::create($request->validated());
$newpost->tags()->sync($request->tags);
return redirect(route('home'));
}
但是为什么它会抱怨时间戳,当我从迁移中删除它们并指定我也没有在模型中使用任何时间戳时?我错过了什么?
提交的“标签”是多项选择。
【问题讨论】:
-
请不要发布代码图片,只需发布代码:)
-
我会在一秒钟内更新,感谢您的提醒!
-
不用担心,这是一个菜鸟错误 :) 但是,是的,'test' 不是 ID(数字),所以这是你的问题 :)
-
你能分享
$request->tags在$newpost->tags()->sync($request->tags);中的样子吗?请将其添加到问题中;)