Laravel Eloquent:追加查询

3

在 Laravel 中是否可以“追加”查询?

例如,在以下示例代码中是否可以这样做:

function crunchNumbersForToday()
{
    return $this->crunchSomeInformationInRange(Payments::where('created_at', Carbon::now()));
}

function crunchNumbersInRange($range)
{
    $paymentsToCrunch = Payment::where('state', 'payed')->append($range)->get();

    // Work with the payments
}

在这种情况下,created_at字段的where将被附加到查询中,其中state等于payed。这将使得查询变为:where created_at = '2015-07-08 12:00' AND state = payed
1个回答

7

我认为你可以创建一个scope

对于你的代码,在你的Payment模型中应该是这样的:

function scopeToday($query)
{
    return $query->where('created_at', Carbon::now());
}

function scopeNumbersInRange($query)
{
    return $query->where('state', 'payed');

    // Work with the payments
}

然后在代码其他地方调用它,如下:

Payment::numbersInRange()->today()->get();

编辑: 您还可以使它们具有动态性:

function scopeDate($query, $date)
{
    return $query->where('created_at', $date);
}

...

Payment::numersInRange()->date(Carbon::now())->get();

等等。这样你就可以保持作用域的链接。


不完全像“传递查询部分”。但它适合我的问题。 - Matthijn
1
这样,您可以将查询部分(可选)添加到QueryBuilder中。您可以链接任意数量的查询部分并以此构建查询,当然,您也可以使它们动态化。除了$query之外,您还可以传递更多变量,以便在查询中使用它们。(无论是->where()还是其他什么) - Francesco de Guytenaere
我现在当然可以这样做:function doSomething($scopeName) { Payment::$scopeName('param')->get(); } 所以,它已经接近完成了。 - Matthijn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接