0

这是我的表字段(打开),但作为响应,它返回 0 1 但我想要 true false 而不是 0 1

我正在使用阿多尼斯 MySQL

table.boolean('open').notNullable().defaultTo(true).comment('true = open, false = close')

常量模型 = 使用('模型')

class Markup extends Model {
static boot() {
    super.boot()

    this.addTrait('@provider:Lucid/SoftDeletes')
    
}
static getColumns() {
    return ['assignee_id', 'editor_details', 'visibility', 'image_url', 'priority', 'open']
}
comments() {
    return this.hasMany('App/Models/Comment', 'id', 'markup_id')
}

assignee() {
    return this.belongsTo("App/Models/User", "assignee_id", "id")
}
created_by() {
    return this.belongsTo("App/Models/User", 'created_by_id', 'id')
}
resolved_by() {
    return this.belongsTo("App/Models/User", 'resolved_by_id', 'id')
}

}

module.exports = 标记

4

1 回答 1

0

正如@asad-jivani 所说:

Boolean 在 MySQL 中不是一个独特的数据类型。它只是 tinyint 的同义词。您可以做的是在模型中编写一个后挂钩以将 1/0 转换为真/假。

在这些情况下,我使用 laravel/lumen 的属性调用 $casts,这是在模型中指定的。

这是一个没有 $cast to is_draft 字段的示例。

JSON响应:

{
    "areas": [
        {
            "id": 1,
            "is_draft": 1,
            "title": "Example"
        }
    ]
}

要将归档的 is_draft 转换为 true 或 false,我刚刚在我的模型中添加了这个。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Area extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $table = 'areas';

    protected $guarded = [];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */

    protected $casts = [
        'is_draft' => 'boolean',
    ];
}

这是解析的 JSON 响应:

{
    "areas": [
        {
            "id": 1,
            "is_draft": true,
            "title": "Example"
        }
    ]
}

我希望这可以帮助你

于 2021-05-26T01:58:11.143 回答