首页 > 解决方案 > 选择数据和来自 with() 的数据,Laravel

问题描述

我想从中选择一些列和一些数据with(),问题是我只从中获取数据select()

$today = date('Y-m-d', strtotime('-7 days'));

$contracts = Contract::select('
    'contracts.id',
    'contracts.contract_value_exc_VAT_total',
    'customers.account_name',
    'users.name',
    )
    ->whereHas('dates', function($q) use($today){
        return $q->whereDate('date', '>=', $today)
            ->where(function($q) {
                $q->where('lkp_contract_date_tag_id', 4)
                    ->orwhere('lkp_contract_date_tag_id', 7);
            });
    })
    ->with(['dates' => function($q){
        $q->select('id', 'date');
    }])
    ->join('customers','contracts.customer_id', 'customers.id')
    ->leftJoin('users','contracts.account_manager_select', 'users.id')
    ->get();

return response()->json($contracts);

从响应中,日期为空

//date....
dates: []
//date...

标签: eloquentlaravel-7

解决方案


您可以在不使用select()

您可以在ContractModel. 从数据库中获取数据后,您始终可以处理数据,并以您想要返回的格式对其进行操作。

有两种选择可以做到这一点

我建议后者,因为它更方便。

对于他们两个,您都需要先执行此操作。对合同模型进行一些更改。

合同模型.php

// I'm assuming that you have dates relation in the contract(because you've added it in the `with()` for eager loading.)

public function dates(){
...
}

 // Instead of joining while doing the query, add the following 
 // relations in the contract as well.

public function customer(){
    return $belongsTo('App\Customer', 'customer_id', 'id');
}

public function accountManagerSelect(){
    return $belongsTo('App\User', 'account_manager_select', 'id');
}

这就是您使用 API 资源方法的方式。

创建合同 API 资源。这就是 toArray() 方法应该是的样子。

toArray() {
  // Get the dates in the format you want. I'have added the below 
  // format by considering the 'select' statement you added for 
  // dates.

  $dates = [];
  // will use the relation dates, to get the associated dates.
  foreach($this->dates as $date){
     array_push($dates, [
         'id' => $date->id,
         'date' => $date->date,
     ]);
  }


  return [
    'id' => $this->id, // id of the contract.
    'contract_value_exc_VAT_total' => $this
                              ->contract_value_exc_VAT_total, 
    'account_name' => $this->account_name, 
     // This will use the accountManagerSelect relation to get the 
     // User instance and then you can access the name from that.
    'name' => $this->accountManagerSelect->name,
    'dates' => $dates, // The dates variable that we created earlier.
   ];
}

您需要做的就是使用控制器中的 API 资源返回。

而不是这样做

return response()->json($contracts);

使用 API 资源

return ContractResource::collection($contracts);

推荐阅读