【问题标题】:how to make filter for food by category and subcategory , and once i press on any category i get its food dishes如何按类别和子类别过滤食物,一旦我按下任何类别,我就会得到它的食物菜肴
【发布时间】:2020-11-03 22:43:11
【问题描述】:

使用这些表格我需要进行类别过滤

食物表:迁移

   $table->bigIncrements('id');
            $table->unsignedBigInteger('category_id')->nullable();
            $table->unsignedBigInteger('image_id')->nullable();
            $table->string('name')
            $table->float('price',9,2)->default(0);
            $table->float('offer_price',9,2)->nullable()->default(0);

            $table->boolean('visible')->default(0);
            $table->timestamps();

类别表:迁移


Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('parent_id')->nullable();
            $table->unsignedBigInteger('image_id')->nullable();
            $table->boolean('visible')->default(0);
            $table->timestamps();
        });

食物模型关系

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

类别模型关系

 public function food()
    {
        return $this->hasMany(Food::class)->orWhereIn('category_id' , $this->subcategory()->pluck('id')->toArray())->visible();
    }
    public function subcategory()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }
````[When clicking on any category it should show food, that related to the category I clicked on ][1]


  [1]: https://i.stack.imgur.com/zpVb8.png

【问题讨论】:

  • 你需要用 Ajax,onChange 事件来做到这一点

标签: ajax laravel laravel-7


【解决方案1】:

你可以在你的控制器中简单地做到这一点

公共功能索引(请求$request) {

$query=Food::query();

// 按类别ID过滤

if ($request->has('category_id')){

$query->whereCategoryId($request->get('category_id')); }`

//排序和执行

$query=$query->orderBy('id','DESC');

return response($query); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2019-08-17
    • 2015-02-25
    • 1970-01-01
    相关资源
    最近更新 更多