来自现有mySQL数据库的Laravel / PHP JSON格式

时间:2014-10-26 12:49:25

标签: php mysql json laravel

我开始使用Laravel和PHP,我正在使用“查询生成器”#39; Laravel中查询现有mySQL数据库的方法。

    public function showApi($id)
    {   
    $data = DB::table('Customers')->where('ID', $id)->get(); //Gets specific records

    return $data;
    }

这将生成一个对象数组和以下JSON预览:

我真的在寻找(实际上用于消费)以下格式:

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在模型转换为数组(或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,然后让所有其他模型从中扩展。

最后,您的控制器方法如下所示:

public function showApi($id)
{   
    $customers = Customer::where('ID', $id)->get(); //Gets specific records

    return Response::json($customers);
}

修改

正如MarcinNabiałek在评论中指出的那样,你的专栏ID有点特别。 Laravel会将其转换为i_d。所以为了避免我们需要将其排除

foreach($attributes as $key => $value){
    if($key == 'ID'){
        $array['id'] = $value;
    }
    else {
        $newKey = snake_case($key);
        $array[$newKey] = $value;
    }
}

如果您有更多这些“特殊情况”,您也可以使用相同的方法单独处理它们......