簡體   English   中英

如何用新方法擴展Laravel模型,集合?

[英]How to Extend Laravel Model, Collection with New Method?

我在控制器方法中為訪客模型應用了一些過濾器。

$filterRules = array();
array_push($filterRules, ['shop_id', '=', $storeId]);

if ($datePeriod == '0' ) 
{
    // calc all period
} else {
    array_push($filterRules, ['created_at', '>=', Carbon::now()->subMinutes($datePeriod)]);
}

$count = Visitor::where($filterRules)->count();

它可以正常工作,但是現在我有了另一個控制器,需要在其中將相同的過濾器應用於Visitor模型,並且我不想重復代碼。

移至此代碼的最佳位置在哪里?

a)向模型添加新方法(Visitor.php)

要么

b)創建一個幫助文件

您可以為此使用Elouquent Scope。 這是一個例子

public function scopeFilterRules($query, $storeId)
{
    $filterRules = array();
    array_push($filterRules, ['shop_id', '=', $storeId]);

    if ($datePeriod == '0' ) {
        // calc all period
    } else {
        array_push($filterRules, ['created_at', '>=', Carbon::now()->subMinutes($datePeriod)]);
    }

    return $query->where($filterRules);
}

現在您可以在應用程序中的任何位置使用它

Visitor::filterRules($storeid)->count();

欲獲得更多信息

https://laravel.com/docs/5.6/eloquent#query-scopes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM