我的数据库中有两个不同的表products
和Ppurchases
(库存明细),并使用以下控制器来获取库存清单。
public function stockapi($id)
{
$data = Ppurchase::where('product_id',$id)->get();
$json_data = json_encode($data);
$data = view('inventory::api.productapi', compact('json_data'));
return response($data)->header("Content-Type","application/json; charset=utf-8");
}
我正在关注JSON:
[
{
"id": 54,
"product_id": 1,
"purchase_id": 45,
"batch": "32",
"manufacture_date": "2017-10-16",
"expiry_date": "2017-10-16",
"quantity": 32,
"invoice_price": 32,
"selling_price": 3,
"product_discount": 32,
"created_at": "2017-10-24 05:31:48",
"updated_at": "2017-10-24 05:31:48"
},
{
"id": 56,
"product_id": 1,
"purchase_id": 46,
"batch": "33",
"manufacture_date": "2017-10-23",
"expiry_date": "2017-10-25",
"quantity": 32,
"invoice_price": 23,
"selling_price": 23,
"product_discount": 23,
"created_at": "2017-10-24 07:46:55",
"updated_at": "2017-10-24 07:46:55"
},
{
"id": 57,
"product_id": 1,
"purchase_id": 47,
"batch": "df",
"manufacture_date": "2017-10-10",
"expiry_date": "2017-10-03",
"quantity": 100,
"invoice_price": 100,
"selling_price": 100,
"product_discount": 100,
"created_at": "2017-10-24 11:58:27",
"updated_at": "2017-10-24 11:58:27"
}
]
现在我的问题从这里开始,
1)如何以人类可读的格式显示这些expiry_date
和manufacture_date
?
2)如何获取剩余日期最少的产品batch
到期? (另外)
答案 0 :(得分:1)
将expiry_date
和manufacture_date
显示为人类可读格式,您可以撰写Accessor
。
您还可以使用Accessor引入新属性,以查找剩余的最少日期到期
我想你有这样的模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Ppurchase extends Model
{
public function getExpiryDateAttribute($value)
{
return Carbon::parse($value)->diffForHumans();
}
public function getManufactureDateAttribute($value)
{
return Carbon::parse($value)->diffForHumans();
}
public function getRemainingDaysAttribute()
{
return Carbon::parse($this->expiry_date)->diffForHumans(Carbon::parse($this->manufacture_date));
}
}
使用此功能,您将获得人类可读格式的日期,您将获得一个新属性remaining_days
,您可以根据需要使用该属性来过滤集合
有关详细信息,我建议您阅读此内容。 https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor