Php 是否可以在Laravel模型上添加自定义功能?

Php 是否可以在Laravel模型上添加自定义功能?,php,laravel,eloquent,laravel-8,Php,Laravel,Eloquent,Laravel 8,我有一个Orders表,它与一个Movements表有关系,我经常这样做来计算每个订单的几个公共值: $warehouse = 7; $order = Order::find(16111); $entries = Movement::selectRaw("SUM(gross) AS total_gross") ->selectRaw("SUM(net) AS total_net") ->selectRaw("SUM(q

我有一个Orders表,它与一个Movements表有关系,我经常这样做来计算每个订单的几个公共值:

$warehouse = 7;
$order = Order::find(16111);
$entries = Movement::selectRaw("SUM(gross) AS total_gross")
    ->selectRaw("SUM(net) AS total_net")
    ->selectRaw("SUM(qty) AS total_qty")
    ->where('order_id', $order->id)
    ->where('to_id', $warehouse)
    ->first();
$exits = Movement::selectRaw("SUM(gross) AS total_gross")
    ->selectRaw("SUM(net) AS total_net")
    ->selectRaw("SUM(qty) AS total_qty")
    ->where('order_id', $order->id)
    ->where('from_id', $warehouse)
    ->first();
是否可以创建一个自定义函数来查询数据库,如下所示:

$warehouse = 7;
$entries = Order::find(16111)->entries($warehouse);
$exits = Order::find(16111)->exits($warehouse);
如果是这样,怎么做


谢谢你的帮助…

绝对感谢。你要找的东西叫做;它允许您避免在代码中重复复杂的查询

局部作用域允许您定义通用的查询约束集,这些约束集可以在整个应用程序中轻松重用

在模型中编写本地查询范围,就不必再重复这段代码(DRY原则)


这里有一个例子给你一个想法,你需要根据自己的需要调整它

在您的订单型号中:

public function scopeEntries($query)
{
    $warehouse = $this->warehouse; // Take advantage of Eloquent wherever you can

    return $query->movements()->selectRaw("SUM(gross) AS total_gross")
        ->selectRaw("SUM(net) AS total_net")
        ->selectRaw("SUM(qty) AS total_qty")
        ->where('to_id', $warehouse->id);
}

public function scopeExits($query)
{
    $warehouse = $this->warehouse; // Take advantage of Eloquent wherever you can

    return $query->movements()->selectRaw("SUM(gross) AS total_gross")
        ->selectRaw("SUM(net) AS total_net")
        ->selectRaw("SUM(qty) AS total_qty")
        ->where('from_id', $warehouse->id)
        ->where('to_id', $warehouse->id);
}

现在在您的代码中,您可以简单地调用
$order->entries()->first()
来检索第一个条目,但也可以调用
$order->exits()->get()
来检索所有出口。

模型只是继承一些数据库方法的类。你可以在它们里面放任何你想要的函数<代码>公共函数项(){…。你可以通过执行
$this->id
获得你的
id,因为你在类中,并将仓库传递到函数中。你的其余代码将保持不变。完全同意@LobsterBaz,这是一种方法。然而,我在使用它们时总是遇到重构和自动完成的问题。特别是如果你在多个模型上使用相同的名称,我会尝试命名每个模型中的函数,因此它们是唯一的,很容易通过纯文本搜索找到,例如scopeWarehouseExits或scopeWarehoueEntries,但最终它会归结为有多少个模型具有相同的功能Tanks…这正是我所需要的。。