php - 在单个视图中对多个表执行 CRUD 操作
问题描述
我在 Laravel 8 上使用 Livewire,目前有 3 个模型,Category
和SubCategory
3MenuItem
个表。以上所有型号都有单独的 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());
});
}
}
解决方案
我设法解决了上述问题,使用 livewire 的组件功能。为 3 个单独的表创建了 3 个单独的组件,最后使用了master-menu.blade.php
文件中的所有三个组件。使用 livewire 和 laravel 是一种享受。
推荐阅读
- vba - CATIA 中的子级零件出版物
- java - Java 正则表达式抓取最后 5 个字符
- amazon-web-services - 如何将多个 S3 Lambda 触发器订阅到现有存储桶?
- android - CameraX:将照片捕获为位图
- amazon-web-services - AWS RDS CLI describe-db-instances 和可用的 DBInstanceClass 选项
- sql - 查询没有结果数据 TRIGGER 的目的地
- post - Grails 3:通过 POST 绑定多个命令对象
- java - 如何使用云功能在应用程序中使用 Firestore 中的文档名称填充我的微调器?
- python - HTML中的Django If语句没有响应
- java - 我正在尝试制作一个程序,要求用户提供 file.txt 并使用字母的频率来绘制条形图。我是堆栈