首页 > 解决方案 > 在单个视图中对多个表执行 CRUD 操作

问题描述

我在 Laravel 8 上使用 Livewire,目前有 3 个模型,CategorySubCategory3MenuItem个表。以上所有型号都有单独的 livewire 控制器,并分别具有 CRUD 操作的代码。我有单独的视图和路线来编辑上面的表格,它们之间都有一种雄辩的关系。现在我需要在这里做的是,我需要在一个视图中显示所有三个表以执行 CRUD 操作。

我试图通过使用子视图函数来实现这一点,传递视图并使变量可用于特定视图,但它没有成功,我认为这不是这样做的方法,只是在尝试想出一个解决方法。我在下面提到我的模型以供参考。请帮我解决一下这个。非常感谢您的时间!

应用\模型\类别

class Category extends Model
{
    use HasFactory;

    protected $table = "categories";
    protected $fillable = ['sub_category_name'];

    public function SubCategories() {
        return $this->hasMany(SubCategory::class, 'category_id');
    }

    public function MenuItems() {
        return $this->hasManyThrough(
            'MenuItem::class',
            'SubCategory::class',
            'sub_category_id',
            'category_id'
        );
    }
}

应用\模型\子类别

class SubCategory extends Model
{
    use HasFactory;

    protected $table = "sub_categories";
    protected $fillable = ['category_id', 'sub_category_name'];

    public function Categories() {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function MenuItems() {
        return $this->hasMany(MenuItem::class, 'sub_category_id');
    }
}

应用\模型\菜单项

class MenuItem extends Model
{
    use HasFactory;

    protected $table = "menu_items";
    protected $fillable = ['sub_category_id', 'item_name', 'item_description'];

    public function SubCategories() {
        return $this->belongsTo(SubCategory::class, 'sub_category_id');
    }
}

这就是我试图达到上述结果的目的。因为我需要将带有子类别表的视图包含到菜单项表视图中。我使变量可用于该特定视图。

资源\视图\Livewire\菜单项

<div>
    @include('livewire.sub-category')
</div>

App\Providers\AppServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use App\Models\SubCategory;

class AppServiceProvider extends ServiceProvider

    {
        /**
         * Register any application services.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            View::composer('livewire.menu-item', function ($view) {
                $view::with('sub_category_name', SubCategory::orderBy('sub_category_name')->get());
            });
            
        }
    }

标签: phplaravellaravel-8

解决方案


我设法解决了上述问题,使用 livewire 的组件功能。为 3 个单独的表创建了 3 个单独的组件,最后使用了master-menu.blade.php文件中的所有三个组件。使用 livewire 和 laravel 是一种享受。


推荐阅读