在 Laravel 6 中,基于 Eloquent 的修改器的属性类型转换,替换 (bool)

1、在 API 响应中,字段:”processing”: false,。如图1

图1

2、字段 processing 的 类型为 tinyint(1)。其值为 0、1。如图2

图2

3、原有的实现如下


    /**
     *  模型的默认属性值。
     *
     * @var array
     */    protected $attributes = [
        'processing' => 1,
  // ...
    ];


$wpTheme['processing'] = (bool) $wpTheme['theme_installation']['processing'];

4、模型中的 $casts 属性提供了一个便利的方法来将属性转换为常见的数据类型。调整后的实现如下,不再需要明确手动地转换属性类型。

    /**
     *  模型的默认属性值。
     *
     * @var array
     */    protected $attributes = [
        'processing' => true,
        // ...
    ];

    /**
     * 这个属性应该被转换为原生类型.
     *
     * @var array
     */    protected $casts = [
        'processing' => 'boolean',
        // ...
    ];

$wpTheme['processing'] = $wpTheme['theme_installation']['processing'];

5、表中的值为 0 ,响应的 API 的值为 false。符合预期。如图3

图3

永夜