如何在JSON响应中表示MySql zerofill

时间:2018-04-14 12:32:07

标签: php mysql json laravel zerofill

大家好,我想要回复我的列有json响应的zerofill规范,但似乎是php忽略那里的零,所以我尝试使用str_pad做同样的工作zerofill,但它也忽略它! 那么我该如何解决这个问题呢? 这是我的代码

public function getGeneralPost(){
    $post =Post::inRandomOrder()->orderBy('created_at', 'DESC')->get();
    foreach ($post as $item){
        $categories = Category::where('id' , $item->post_subtype)->select('category_title')->first();
        $categories_type = Category::where('id' , $item->post_type)->select('category_title')->first();
        $item->post_subtype = $categories->category_title;
        $item->post_type = $categories_type->category_title;
        $item->id = str_pad($item->id ,10,'0',STR_PAD_LEFT);// here I am usting str_pad     
    }
    $success['posts'] =$post;
    return response()->json(['code'=>'success','success' => $success], $this->successStatus);
}

2 个答案:

答案 0 :(得分:1)

检索数据时,它已忽略零。我认为你需要一个访问器:

function getIdAttribute($value) {
    return str_pad($value, 10, '0', STR_PAD_LEFT);
}

希望这有帮助。

答案 1 :(得分:1)

正如评论中已经指出的那样,id列的int列似乎有一个默认广告,它会恢复您通过str_pad()完成的更改。

为了解决这个问题,您可以将填充的id存储在一个没有强制转换的单独字段中,或者不是更改对象,而是可以获取对象的属性,更改它们并使用他们返回你的结果。

framework code itself开始,也可以在返回对象之前覆盖对象的$keyType属性:

public function getGeneralPost() {
    $post = Post::inRandomOrder()->orderBy('created_at', 'DESC')->get();
    foreach ($post as $item) {
        $categories = Category::where('id' , $item->post_subtype)->select('category_title')->first();
        $categories_type = Category::where('id' , $item->post_type)->select('category_title')->first();
        $item->post_subtype = $categories->category_title;
        $item->post_type = $categories_type->category_title;

        $item->setKeyType('string');
        $item->id = str_pad($item->id ,10,'0',STR_PAD_LEFT);
    }
    $success['posts'] = $post;
    return response()->json(['code'=>'success','success' => $success], $this->successStatus);
}