如何缩短此 eloquent 命令

How to shorten this eloquent command

我已经使用这个 Eloquent 命令从数据库中获取了一些数据 table:

$categories = Category::where('category_type',2)->orWhere('category_type',3)->orWhere('category_type',4)->get();

return view('admin.categories.index', compact('categories'));

所以我想要 234 中的 category_type 但是我想缩短这个命令,所以我改用这个:

$categories = Category::where('category_type',[2,3,4,5])->get();

但它不能正常工作,只显示 category_type of 2!

的数据

所以问题是如何缩短这些 orWhere 命令?有什么办法吗?

尝试 whereIn()...

<?php

$categories = Category::whereIn('category_type',[2,3,4])->get();

return view('admin.categories.index', compact('categories'));

https://laravel.com/docs/8.x/queries#additional-where-clauses

这可能有点矫枉过正,但把你的怒视变成:https://github.com/rinvex/laravel-categories

刚开始的时候挺难的,反而给了很多东西。

请记住,在 laravel 中,您可以在模型中进入 local/global 范围 https://laravel.com/docs/8.x/eloquent#query-scopes

public function scopePopular($query)
{
    return $query->where('votes', '>', 100);
}

您可以通过这种方式链接查询。示例来自文档。想都别想'repository pattern'。在我看来,它违反了上述功能并使您的代码变得一团糟。随便玩玩,在模型中进行查询。

当你发现自己处境艰难,需要从涉及的几个模型中创建一些东西(模型聚合)时,你可能会考虑 services/helpers/WHATEVER。在 MVVM 中为视图模型赋予相同的角色,因为它们为控制器准备数据。

这些是繁重的逻辑类,它们让你的大部分工作落后,它们被controller/command-line/anything调用。