在 Laravel 关系对象上将字符串转换为整数
Posted
技术标签:
【中文标题】在 Laravel 关系对象上将字符串转换为整数【英文标题】:Convert String to integer on Laravel relationship object 【发布时间】:2021-12-14 00:52:42 【问题描述】:我有一个由 qty 作为字符串组成的数组集合,我想要删除 $
符号并将字符串变为整数
"collection": [
"id": 983,
"controlNumber": "4498818",
"ItemNumber": "PS2W12077",
"shipment":
"id": 27,
"Item": "PS2W12077",
"ColorCode": "GRPFR",
"qty": "$1,638"
,
"id": 982,
"controlNumber": "4498818",
"ItemNumber": "PS2W12077",
"shipment":
"id": 27,
"Item": "PS2W12077",
"ColorCode": "GRPFR",
"qty": "$1,638"
,
"id": 981,
"controlNumber": "4498818",
"ItemNumber": "PS2W12077",
"shipment":
"id": 27,
"Item": "PS2W12077",
"ColorCode": "GRPFR",
"qty": "$1,638"
,
"id": 980,
"controlNumber": "4498818",
"ItemNumber": "PS2W12077",
"shipment":
"id": 27,
"Item": "PS2W12077",
"ColorCode": "GRPFR",
"qty": "$1,638"
]
我得到的模型关系如下
public function Openorder()
$object = $this->hasOneThrough(OpenorderImportTemp::class, 'ItemNumber', 'Item');
return $object;
然后在控制器上抓取如下
$openorder_data = OpenorderImportTemp::
select('id', 'controlNumber', 'ItemNumber', )
->with('shipment:id,Item,ColorCode,qty')
// ->groupBy('controlNumber')
->orderby('id', 'desc')
->where('ControlNumber', '!=', '0')
->get();
根据我的需要将字符串更改为整数的任何可能性。我尝试过的如下
$openorder_data = OpenorderImportTemp::
select('id', 'controlNumber', 'ItemNumber', DB::raw("SUM(shipment.qty) as qtysum") )
->with('shipment:id,Item,ColorCode,qty')
// ->groupBy('controlNumber')
->orderby('id', 'desc')
->where('ControlNumber', '!=', '0')
->get();
【问题讨论】:
【参考方案1】:protected $casts = [
'qty' => 'integer',
];
在模型上解决了我的问题。将字符串更改为整数
【讨论】:
以上是关于在 Laravel 关系对象上将字符串转换为整数的主要内容,如果未能解决你的问题,请参考以下文章
编写函数fun,将一个数字字符串转换为一个整数,例如,输入字符串"-1234",则函数把他转换为整数值-1234
c++如何将string字符串按原内容转换为整型int数据 (C++如何判断某字符串数据是否是纯数字)