eloquent - 选择数据和来自 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...
解决方案
您可以在不使用select()
您可以在ContractModel
. 从数据库中获取数据后,您始终可以处理数据,并以您想要返回的格式对其进行操作。
有两种选择可以做到这一点
- 在控制器本身中执行此操作。
- 为合约创建 API 资源。(https://laravel.com/docs/7.x/eloquent-resources#introduction)
我建议后者,因为它更方便。
对于他们两个,您都需要先执行此操作。对合同模型进行一些更改。
合同模型.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);
推荐阅读
- python - 如果差异为负,熊猫系列添加上一行
- javascript - 轻松限制一个承诺返回方法
- wordpress - 启用 NGINX 后,WordPress 博客子目录中的所有帖子都给出 404 Page Not Found
- laravel - vue.js如何在单个axios中调用多个url数据
- mongodb - 如何使用 rust mongodb 驱动程序在 mongodb 中执行 bulkWrite?
- python - Python 2.6 在解析整个脚本之前不会抛出断言错误
- django - 视图课程.views.login 没有返回 HttpResponse 对象。它返回 None 而不是
- unity3d - 使用 LeanTween 游戏对象旋转不超过 360°
- java - 如果我在回收站视图中有数千个项目,那么如何在每个项目上设置项目单击侦听器
- node.js - React-native:无法安装 expo-cli