首页 > 解决方案 > Laravel - 如何使用 API 实现模型功能

问题描述

试图通过 api 响应达到我的模型属性。

这是我的 Customer.php(模型)

class Customer extends Model
{
    public function debt()
    {
        if($this->company_id){
            if($this->company->is_fleet){
                $total = $this->company->fleetOrders->where('status', 1)->sum(function($t){ 
                    return $t->total - $t->discount + $t->vat; 
                });
    
                $receipts = $this->company->allReceipts->whereNull('fleet_id')->sum('price');
                return money_formatter($total-$receipts);
            }

            $vehicles = $this->company->vehicles->whereNotNull('fleet_id')->pluck('id')->toArray();
            $total = $this->company->orders->whereNotIn('vehicle_id', $vehicles)->where('status', 1)->sum(function($t){ 
                return $t->total - $t->discount + $t->vat; 
            });

            $receipts = $this->company->allReceipts->whereNull('fleet_id')->sum('price');
            return money_formatter($total-$receipts);
            
        }

        $vehicles = $this->customerVehicles->whereNotNull('fleet_id')->pluck('id')->toArray();
        $total = $this->customerOrders->where('status', 1)->whereNotIn('vehicle_id', $vehicles)->sum(function($t){ 
            return $t->total - $t->discount + $t->vat; 
        });
        $receipts = $this->customerReceipts->whereNull('fleet_id')->sum('price');
        return money_formatter($total-$receipts);
    }
}

这就是我想要做的。我需要从其他关系中获得我的“债务”功能。但不能让它健康。

  public function index()
    {
        $d = $this->request->all();
        $parameters = $this->request->query();
        $firm_id = $this->request->user()->firm_id;
        $user = $this->request->user();

        $tires = Order::where('firm_id', $firm_id)
        ->with('customer', 'customer.debt')->get()
....

标签: laravelapi

解决方案


你不需要customer.debt,因为它实际上不是一个关系。此方法已在客户上可用。

当您循环时,$tires您可以通过以下方式访问该方法$tire->customer->debt()

我猜你不能像这样传递这种关系。您必须在控制器或资源集合中准备该数据。


推荐阅读