英文:
Laravel Filament adding data to multiple tables
问题
我需要在我使用Laravel filament开发的项目中,使用belongsToMany向多个表中添加数据。
示例数据库:
- 分类(Category):id,名称(name)
- 动画(Anime):id,名称(name),描述(description)
- 动画分类(AnimeCategory):id,分类id(category_id),动画id(anime_id)
代码:
- 动画资源(Anime Resource): [链接](https://codeshare.io/3AEg7v)
- 动画模型(Anime Model): [链接](https://codeshare.io/mpydBj)
- 分类模型(Category Model): [链接](https://codeshare.io/lorKBD)
- 动画分类模型(AnimeCategory Model): [链接](https://codeshare.io/r9A3BY)
在动画表中,我得到了“categoryId未找到”的错误。
在动画资源中找到:
```php
Select::make('categoryId')
->label('选择分类')
->placeholder('选择分类')
->required()
->multiple()
->options(function () {
return Category::all()->pluck('title', 'id');
}),
我该如何将所选的多个分类id数据添加到动画分类表中?
<details>
<summary>英文:</summary>
I need to add data to more than one table with belongsToMany in the project I developed with Laravel filament.
Example DB:
- Category: id, name
- Anime: id, name, description
- AnimeCategory: id, category_id, anime_id
Code:
- Anime Resource: https://codeshare.io/3AEg7v
- Anime Model: https://codeshare.io/mpydBj
- Category Model: https://codeshare.io/lorKBD
- AnimeCategory Model: https://codeshare.io/r9A3BY
I am getting categoryId not found error in Anime Table.
Found in Anime Resource:
Select::make('categoryId')
->label('Kategori seçiniz')
->placeholder('Kategori Seçiniz')
->required()
->multiple()
->options(function () {
return Category::all()->pluck('title', 'id');
}),
How can I add selected multi-category id data to AnimeCategory table?
</details>
# 答案1
**得分**: 0
解决方案
Anime模型
```php
public function categories()
{
return $this->belongsToMany(Category::class, 'anime_categories', 'animeId', 'categoryId');
}
Anime资源的CategoryId多选
Select::make('categoryId')
->relationship('categories', 'title')
->label('选择分类')
->placeholder('选择分类')
->required()
->multiple()
->preload()
英文:
Solution
Anime Model
public function categories()
{
return $this->belongsToMany(Category::class, 'anime_categories', 'animeId', 'categoryId');
}
Anime Resource CategoryId Multiple Select
Select::make('categoryId')
->relationship('categories', 'title')
->label('Kategori seçiniz')
->placeholder('Kategori Seçiniz')
->required()
->multiple()
->preload()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论