'Adonisjs How to cast boolean to false and true in a model instead of 0 or 1?
This is my table field (open) but in response, it returns 0 1 but I want true false instead of 0 1
I am using adonis 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 = Markup
Solution 1:[1]
As @asad-jivani said:
Boolean isn't a distinct datatype in MySQL; it's just a synonym for tinyint. what you can do is write an after hook in your model to convert 1/0 to true/false.
In these cases I use a property of laravel/lumen calls $casts, this is specified in the model.
here is an example without the $cast to is_draft field.
JSON Response:
{
"areas": [
{
"id": 1,
"is_draft": 1,
"title": "Example"
}
]
}
to convert the filed is_draft to true or false I just added this in my model.
<?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',
];
}
and here is the parsed JSON Response:
{
"areas": [
{
"id": 1,
"is_draft": true,
"title": "Example"
}
]
}
I hope this helps you ?
Solution 2:[2]
This just a simple fix. you just have to do this in your column.
@column({ serialize: Boolean })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jonathan |
Solution 2 | Hasibur Rahman |