繁体   English   中英

如何获得 Laravel Query Builder 结果为 integer

[英]How to get Laravel Query Builder result as integer

我正在使用 Laravel 查询生成器查询 MySQL 数据库,但它返回 integer 值作为字符串值。

我有以下查询。

$query = DB::table('store_products')->select('products.id', 'products.name', 'products.unit_type', 'products.price', 'products.image_path', 'products.is_popular', 'store_products.price AS store_price')
           ->join('products', 'products.id', '=', 'store_products.product_id')
           ->join('product_categories', 'product_categories.product_id', '=', 'store_products.product_id')
           ->where('store_products.store_id', $store_id)
           ->where('store_products.product_id', $product_id);

此处查询获取给定store_idStore_Products中存在的 Product。

问题是,当我使用查询生成器时,它以string形式返回id (这是产品的主键)。 看起来演员表有问题。

我怎么解决这个问题?

非常感谢你提前。

转换不是解决方案,而是解决问题的方法。 你的实际问题是缺少mysqlnd插件。

检查是否安装了mysqlnd

$ sudo dpkg -l | grep 'mysqlnd'

如果没有安装,你需要安装它(假设你有php5)

$ sudo apt-get install php5-mysqlnd

这些命令适用于ubuntu 如果您还有其他内容,只需将它们转换为适当的操作系统即可。

当通过select获取时,它会使用底层驱动程序返回的原始数据填充$attribute内部属性,因此通常将MySQL驱动程序配置为将所有列作为字符串返回。 这里它不会将id属性强制转换为整数。

您必须手动将其转换为整数。 您可以使用(int) $variable语法将其转换为动态的整数,您可以在其中访问模型的属性,或者您可以为此创建一个mutator。

public function getIdAttribute($value)
{
    return (int) $value;
}

或者你可以投射你的属性

protected $casts = [
    'id' => 'integer',
];

这不知何故发生在我做 SUM、IF 和其他东西的原始查询中。

但我不想在 model 中为访问器或强制转换添加更多代码,例如 Zayn Ali 针对此特定查询的回答。

所以我的解决方法是使用MySQL cast function

$query->selectRaw('CAST(column_1 AS UNSIGNED) AS col1')

使用原始查询时,请确保您了解 SQL 注入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM