这种雄辩方法的查询范围?

我在我的项目中创建了一个过滤方法,我使用此方法过滤了数据,但现在我想使用 laravel 中的 queryScope 方法重构代码,任何人都可以建议我如何重构此代码。这段代码运行良好。


这是我的控制器索引方法


    public function index(Request $request)

    {

        $status = Ticket_status::pluck('name');


        $tickets = Ticket::with('users','ticketStatus','ticketType','tbl_contacts')

                    ->where('user_id','=',Auth::user()->id)

                    ->latest();


        if (request('Open')) {

            $tickets = $tickets->where('status_id',1)->get();

        } elseif (request('Pending')) {

            $tickets = $tickets->where('status_id',2)->get();

        } elseif (request('Close')) {

            $tickets = $tickets->where('status_id',3)->get();

        } else {

            $tickets = $tickets->get();

        }


        return view('ticketing.user.index',compact('tickets','status'));

    }

这是我的刀片文件..在这个文件中,所有代码都运行良好,但我想进行一些重构


<div class="col-md-8">

                            <a

                                href="{{route('tickets.index')}}"

                                class="btn btn-sm btn-outline-secondary mr-1">

                                All

                            </a>

                            @foreach ($status as $status_name)

                                <a

                    href="/tickets?{{Str::lower($status_name)}}={{ Str::lower($status_name) }}"

                     class="btn btn-sm btn-outline-secondary mr-1">

                                    {{$status_name}}

                                </a>

                            @endforeach

  

                        </div>


慕尼黑8549860
浏览 53回答 1
1回答

Helenr

您可以local在模型上定义范围来重构查询。以下是一些:class Ticket extends Model{use SoftDeletes;public function scopeByAuthUser($query){&nbsp; &nbsp; return $query->where('user_id','=', \Auth::user()->id);}public function scopeOpen($query){&nbsp; &nbsp; return $query->where('status_id', 1);}public function scopePending($query){&nbsp; &nbsp; return $query->where('status_id', 2);}public function scopeClose($query){&nbsp; &nbsp; return $query->where('status_id', 2);}&nbsp;}以下是重构您的条件的方法:&nbsp;// for the first query&nbsp;$tickets = Ticket::with('users','ticketStatus','ticketType','tbl_contacts')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->byAuthUser()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->latest();&nbsp;if(request('Open') || request('Pending') || request('Close')) {&nbsp; &nbsp;$scope = strtolower(request('Open') ?? request('Pending') ?? request('Close'));&nbsp; &nbsp;$tickets = $tickets->{$scope}()->get();&nbsp;} else {&nbsp; $tickets = $tickets->get();&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP