【问题标题】:Adonisjs How to cast boolean to false and true in a model instead of 0 or 1?Adonisjs 如何在模型中将布尔值转换为 false 和 true 而不是 0 或 1?
【发布时间】:2021-05-25 12:39:42
【问题描述】:

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

我正在使用阿多尼斯 MySQL

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

const Model = use('Model')

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 = 标记

【问题讨论】:

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

标签: javascript mysql adonis.js lucid adonisjs-ace


【解决方案1】:

正如@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"
        }
    ]
}

希望对你有帮助?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2013-10-11
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多