Laravel 灯丝 3.x |依赖选择如何在数据透视表中保存数据?

问题描述 投票:0回答:1

我使用数据透视表创建了 tbl_products 与 tbl_sub_categories 表的多对多关系。 和 sub_categories 取决于类别,我能够获得相关数据很好。但 sub_categories 下拉列表无法在数据透视表中保存数据。

灯丝资源代码

Select::make('category_id')
                ->live()
                ->label('Category')
                ->dehydrated(false)
                ->options(Category::pluck('title','id'))
                ->required(),

                Select::make('sub_category_id')
                ->required()
                ->relationship('sub_categories','id') // unable to get subcategories list when i use this code
                ->multiple()
                ->label('Sub Categories')
                ->placeholder(fn (Forms\Get $get): string => empty($get('category_id')) ? 'First select category' : 'Select an option')
                ->options(function (Forms\Get $get) {
                    return SubCategory::where('category_id', $get('category_id'))->pluck('title', 'id');
                })->reactive(),

产品型号关系

 public function subCategories()
    {
        return $this->belongsToMany(SubCategory::class, 'sub_category_product');
    }

子类别模型关系

 public function products()
    {
        return $this->belongsToMany(Product::class, 'sub_category_product');
    }

数据透视表迁移

<?php

use App\Models\Product;
use App\Models\SubCategory;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('sub_category_product', function (Blueprint $table) {
            $table->foreignIdFor(SubCategory::class);
            $table->foreignIdFor(Product::class);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('sub_category_product');
    }
};
many-to-many relationship laravel-filament laravel-11 filamentphp
1个回答
0
投票

如果您使用关系函数,则不需要选择组件上的选项函数,您可以使用第三个参数(modifyQueryUsing参数)修改查询,如下所示:

Select::make('sub_category_id')
    ->required()
    ->relationship(
        'subCategories', // name of the relationship
        'title', // column to use for the label
        fn(Builder $query, Forms\Get $get) => $query
            ->where('category_id', $get('category_id')) // you can filter subcategories by category using this
    )
    ->multiple()
    ->label('Sub Categories')
    ->live()
    ->placeholder(fn (Forms\Get $get): string => empty($get('category_id')) ? 'First select category' : 'Select an option'),
© www.soinside.com 2019 - 2024. All rights reserved.