【问题标题】:How to define the data type before returning JSON data for api backend in laravel如何在laravel中为api后端返回JSON数据之前定义数据类型
【发布时间】:2019-02-18 02:43:36
【问题描述】:

我开发了一个用于移动设备的 api 后端。在我将代码放在另一个域中开始部署之前,这一切都很好。突然我注意到,user_id 数据类型之一已更改为string,之前是int,并且一切正常。

这就是我在 laravel 控制器中所做的事情

  $clubs=Club::with(['users' => function($q){
        $q->select('id','profilePic');
    }])->with('leagueCount')
    ->get();

   return response()->json([
        'success' => true,
        'clubs' => $clubs,
    ],200);

它给了我这样的结果

success: true,
clubs: [
{
id: 8,
user_id: "34",  // this shouldn't be a string. It should be int.
 clubName: "PADELCENTER",
 clubDesc: "Testclub",
 color: "#424242",
 logo: "logotouse.png",
 created_at: "2018-05-12 07:44:40",
 updated_at: "2018-05-12 07:44:40",
 users: {
   id: 34,
   profilePic: "20KdcnX5Gb2dSfunwT8JtmBvcVopDmUwKmQ7XeUI.png"
 },
 league_count: [
 {
   id: 31,
   club_id: "8",
   total: "1"
 }
]
},

你可以看到 user_id 是一个string 它应该是int

无论如何我在模型中或某处强制设置数据类型?

[注意:user_id 是 int 并且在数据库中作为用户表的外键是无符号的。]

非常感谢。

【问题讨论】:

标签: php laravel laravel-5.6


【解决方案1】:

你可以使用 Eloquent mutators 将属性转换为整数,如下所示:

class Club extends Model
{
    protected $casts = [
        'user_id' => 'integer',
    ];
}

【讨论】:

  • 非常感谢 :)
【解决方案2】:

有两种方法可以解决这个问题

在您的模型中,您可以像

一样从数据库中转换输出
$casts = [
'user_id' => 'int'
];

或者你可以使用资源php artisan make:resource Club

然后你可以简单地使用toArray方法

  public function toArray($request)
    {
        return [
            // do casting in here
        ];
    }

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2021-01-02
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多