我开始使用 Laravel 和 PHP,我正在使用 Laravel 中的“查询生成器”方法来查询现有的 mySQL 数据库。
public function showApi($id)
{
$data = DB::table('Customers')->where('ID', $id)->get(); //Gets specific records
return $data;
}
这会生成一个对象数组和以下 JSON 预览:
我真的在寻找(并且实际使用)以下格式:
如有任何帮助,我们将不胜感激。
最佳答案
在模型转换为数组(或 json 对象)时更改模型属性的最佳方法是覆盖模型中的 toArray()
方法。所以如果你还没有,你将不得不开始使用 Eloquent models .
您的模型 - Customer.php
class Customer extends Eloquent {
protected $table = 'Customer' // you'll need that because you're table differs from the convention ('customer')
public function toArray(){
$attributes = parent::toArray();
$array = array();
foreach($attributes as $key => $value){
$newKey = snake_case($key);
$array[$newKey] = $value;
}
return $array;
}
}
我们在这里所做的只是从您的父级获取属性数组,然后遍历它并将键从 StudlyCase 更改为 snake_case
如果您的所有模型都需要此功能,最好创建一个具有此方法的 BaseModel
,然后让所有其他模型从中扩展。
最后,您的 Controller 方法将如下所示:
public function showApi($id)
{
$customers = Customer::where('ID', $id)->get(); //Gets specific records
return Response::json($customers);
}
编辑
正如 Marcin Nabiałek 在评论中指出的那样,您的列 ID
有点特别。 Laravel 会将其转换为 i_d
。所以为了避免我们需要排除它
foreach($attributes as $key => $value){
if($key == 'ID'){
$array['id'] = $value;
}
else {
$newKey = snake_case($key);
$array[$newKey] = $value;
}
}
如果你有更多这样的“特殊情况”,你也可以使用相同的方法分别处理它们......
关于php - 来自现有 mySQL 数据库的 Laravel/PHP JSON 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26573134/