Laravel Filament 向多个表添加数据

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

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-&gt;belongsToMany(Category::class, &#39;anime_categories&#39;, &#39;animeId&#39;, &#39;categoryId&#39;);
}

Anime Resource CategoryId Multiple Select

Select::make(&#39;categoryId&#39;)
    -&gt;relationship(&#39;categories&#39;, &#39;title&#39;)
    -&gt;label(&#39;Kategori se&#231;iniz&#39;)
    -&gt;placeholder(&#39;Kategori Se&#231;iniz&#39;)
    -&gt;required()
    -&gt;multiple()
    -&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:

确定