有一个模型Post
,在其中我创建了与流派表的多对多关系
class Post extends Model
{
use HasFactory;
protected $guarded = false;
public function genres(): BelongsToMany
{
return $this->belongsToMany(Genres::class);
}
}
store
我向控制器方法发出发布请求PostContoller
并验证输入数据StoreRequest
public function store(StoreRequest $request)
{
$data = $request->validated();
$post = Post::create($data);
return PostResource::make($post)->resolve();
}
表迁移posts|genres|genre_post
看起来像这样
posts
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('alias')->nullable()->unique();
$table->string('title', 512)->nullable();
$table->year('year')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
genres
Schema::create('genres', function (Blueprint $table) {
$table->tinyIncrements('id');
$table->string('name');
});
genre_post
Schema::create('genre_post', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->nullable();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->unsignedTinyInteger('genre_id')->nullable();
$table->foreign('genre_id')->references('id')->on('genres')->onDelete('cascade');
});
当我尝试创建记录时出现错误 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'genres' in 'field list'
我知道posts
我的表中没有字段genres
,但是我该如何做,以便在验证字段后,我可以简单地发送日期以类似的方式创建帖子Post::create($data)
?是否有可能做到这一点以及如何通过关系来实现它?
否则我真的不想写这样的脚布(而且我认为这是不正确的):
if ($title = $request->has('title')) {
// ...
}
if ($genres = $request->has('genres')) {
foreach(explode(',', $genres) as $genre) {
$this->post->genres()->attach($genre, [
'post_id' => $post_id,
'genre_id' => $genre
]);
}
}