Laravel Filament 向多个表添加数据

huangapple go评论78阅读模式
英文:

Laravel Filament adding data to multiple tables

问题

  1. 我需要在我使用Laravel filament开发的项目中,使用belongsToMany向多个表中添加数据。
  2. 示例数据库:
  3. - 分类(Category):id,名称(name
  4. - 动画(Anime):id,名称(name),描述(description
  5. - 动画分类(AnimeCategory):id,分类idcategory_id),动画idanime_id
  6. 代码:
  7. - 动画资源(Anime Resource): [链接](https://codeshare.io/3AEg7v)
  8. - 动画模型(Anime Model): [链接](https://codeshare.io/mpydBj)
  9. - 分类模型(Category Model): [链接](https://codeshare.io/lorKBD)
  10. - 动画分类模型(AnimeCategory Model): [链接](https://codeshare.io/r9A3BY)
  11. 在动画表中,我得到了“categoryId未找到”的错误。
  12. 在动画资源中找到:
  13. ```php
  14. Select::make('categoryId')
  15. ->label('选择分类')
  16. ->placeholder('选择分类')
  17. ->required()
  18. ->multiple()
  19. ->options(function () {
  20. return Category::all()->pluck('title', 'id');
  21. }),

我该如何将所选的多个分类id数据添加到动画分类表中?

  1. <details>
  2. <summary>英文:</summary>
  3. I need to add data to more than one table with belongsToMany in the project I developed with Laravel filament.
  4. Example DB:
  5. - Category: id, name
  6. - Anime: id, name, description
  7. - AnimeCategory: id, category_id, anime_id
  8. Code:
  9. - Anime Resource: https://codeshare.io/3AEg7v
  10. - Anime Model: https://codeshare.io/mpydBj
  11. - Category Model: https://codeshare.io/lorKBD
  12. - AnimeCategory Model: https://codeshare.io/r9A3BY
  13. I am getting categoryId not found error in Anime Table.
  14. 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');
}),

  1. How can I add selected multi-category id data to AnimeCategory table?
  2. </details>
  3. # 答案1
  4. **得分**: 0
  5. 解决方案
  6. Anime模型
  7. ```php
  8. public function categories()
  9. {
  10. return $this->belongsToMany(Category::class, 'anime_categories', 'animeId', 'categoryId');
  11. }

Anime资源的CategoryId多选

  1. Select::make('categoryId')
  2. ->relationship('categories', 'title')
  3. ->label('选择分类')
  4. ->placeholder('选择分类')
  5. ->required()
  6. ->multiple()
  7. ->preload()
英文:

Solution

Anime Model

  1. public function categories()
  2. {
  3. return $this-&gt;belongsToMany(Category::class, &#39;anime_categories&#39;, &#39;animeId&#39;, &#39;categoryId&#39;);
  4. }

Anime Resource CategoryId Multiple Select

  1. Select::make(&#39;categoryId&#39;)
  2. -&gt;relationship(&#39;categories&#39;, &#39;title&#39;)
  3. -&gt;label(&#39;Kategori se&#231;iniz&#39;)
  4. -&gt;placeholder(&#39;Kategori Se&#231;iniz&#39;)
  5. -&gt;required()
  6. -&gt;multiple()
  7. -&gt;preload()

huangapple
  • 本文由 发表于 2023年2月19日 17:47:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定