Column Types
Entities map each database column type to a PHP property type. This page lists the types that need extra handling, such as bigint, decimal, enum, json, and the date and time types.
Most of the code on this page is generated by build:entity [-k]. You can adjust the generated types by hand, or write and extend the code yourself.
BigInt Columns
Windwalker returns bigint values as strings by default. A MySQL bigint and a 64-bit PHP int have the same width, so you can change the property to int when your values fit in 64 bits.
// By default, Windwalker generates bigint columns as strings
#[Column('view_count')]
public string $viewCount = '0';
// You can manually change to int instead
#[Column('view_count')]
public int $viewCount = 0;To handle values of any length, use brick/math's BigInteger. The BigIntegerEntityMemberSubscriber rewrites bigint properties to BigInteger when the entity generator builds them. Register it under listeners in etc/app/console.config.php:
// etc/app/console.config.php
use Windwalker\Core\Generator\Subscriber\BigIntegerEntityMemberSubscriber;
'listeners' => [
BigIntegerEntityMemberSubscriber::class,
],The subscriber only changes code generated by the entity generator. Regenerate the entity to apply it to existing bigint columns.
use Brick\Math\BigInteger;
#[Column('id'), PK, AutoIncrement]
#[Cast(BigInteger::class)]
public BigInteger $id {
set(BigInteger|string|float|int|null $value) => $this->id = \Windwalker\try_big_integer($value);
}
#[Column('total')]
#[Cast(BigInteger::class)]
public BigInteger $total {
set(BigInteger|string|float|int|null $value) => $this->total = \Windwalker\try_big_integer($value);
}Decimal Columns
By default, decimal values are strings, because PHP float cannot hold their precision. To use brick/math's BigDecimal instead, register BigDecimalEntityMemberSubscriber the same way:
// etc/app/console.config.php
use Windwalker\Core\Generator\Subscriber\BigDecimalEntityMemberSubscriber;
'listeners' => [
BigDecimalEntityMemberSubscriber::class,
],The generated property then uses BigDecimal with arbitrary precision. When the column does not report a scale, the subscriber uses 4 digits and RoundingMode::HalfUp. If you want to change the scale or rounding mode, use create() function:
'listeners' => [
\Windwalker\DI\create(
BigDecimalEntityMemberSubscriber::class,
scale: 2,
roundingMode: \Brick\Math\RoundingMode::HalfUp
)
],The output of build:entity looks like this:
#[Column('price')]
#[CastNullable(BigDecimal::class)]
public ?BigDecimal $price = null {
set(BigDecimal|string|float|int|null $value) => $this->price = \Windwalker\try_big_decimal($value, 2, \Brick\Math\RoundingMode::HalfUp);
}Enum Columns
Store an enum in a tinyint or varchar column, and map it to a PHP enum. The g enum command generates the enum class, as described in Enum.
namespace App\Enum;
enum ItemState: int
{
case DISABLED = 0;
case ENABLED = 1;
}The entity then uses the enum as the property type.
#[Column('state')]
public ItemState $state = ItemState::DISABLED;
// Load and compare
if ($sakura->state === ItemState::ENABLED) {
// ...
}With the -k option, build:entity adds a property hook to the enum property. The hook accepts the enum case or the raw backed value, such as 1, and converts it to the enum.
#[Column('state')]
public ItemState $state {
set(ItemState|int|string $value) {
$this->state = ItemState::wrap($value);
}
}See Modeling for the full build:entity -k output and how to add get hooks.
To add labels, colors, or other display data to an enum, see Enum.
TIP
Use a backed enum for stored values. The stored value is a stable integer or string, and the case name can change without a migration.
JSON and Record Columns
Columns of type json become array properties with #[JsonObject]. Windwalker generates this attribute automatically, and you can change it to #[JsonArray] if the value is a list.
use Windwalker\ORM\Attributes\JsonArray;
use Windwalker\ORM\Attributes\JsonObject;
#[Column('options')]
#[JsonObject]
public array $options = [];
#[Column('tags')]
#[JsonArray]
public array $tags = [];If you want to use an object to wrap json values, create a class that implements RecordInterface and uses RecordTrait.
class UserOptions implements \Windwalker\Data\RecordInterface
{
use \Windwalker\Data\RecordTrait;
public function __construct(
public string $theme = 'light',
public bool $notifications = true,
) {
}
}Next, change the property type to the class. Then run build:entity -k to generate the hook, which looks like this:
#[Column('options')]
#[JsonObject]
public UserOptions $options {
set(UserOptions|array $value) {
$this->options = UserOptions::wrap($value);
}
}The Casting system will automatically convert the JSON to a UserOptions object when reading, and convert it back to JSON when saving.
If you want to wrap values by a non-record class, you must manually add #[Cast(MyClass::class)] to the property.
#[Column('options')]
#[JsonObject]
#[Cast(MyClass::class)]
public MyClass $options {
set(MyClass|array $value) {
$this->options = $value instanceof MyClass ? $value : new MyClass($value);
}
}See Object Serialization for how these objects are serialized.
Lazy Record Objects
Add a get hook when you want an empty object instead of null. The hook creates the object on first read and stores it in the property.
#[Column('address')]
#[JsonObject]
public AddressInfo $address {
set(AddressInfo|array|null $value) =>
$this->address = AddressInfo::wrap($value);
get => $this->address ??= new AddressInfo();
}Reading the property changes it, so an entity saved after a read will store the new empty object. Use this pattern only when the code always needs the object.
Hiding Properties from Records
A Record in a JSON column is saved with json_encode(). Computed properties are derived from other data, so they are hidden by default. This keeps the JSON column free of duplicate values.
Use #[Invisible] for a regular property that must not be dumped or encoded, such as a cached value or a secret.
use Windwalker\Utilities\Attributes\Invisible;
class UserOptions implements \Windwalker\Data\RecordInterface
{
use \Windwalker\Data\RecordTrait;
public string $theme = 'light';
#[Invisible]
public string $apiToken = '';
}INFO
#[Invisible] wins over #[Expose]. An invisible property stays hidden even when you add #[Expose] to it.
DateTime Columns
datetime columns become ?Chronos properties with #[CastNullable(ServerTimeCast::class)]. The cast reads and writes the value in the server time zone and stores it as UTC.
use Windwalker\Core\DateTime\Chronos;
use Windwalker\Core\DateTime\ServerTimeCast;
use Windwalker\ORM\Attributes\CastNullable;
#[Column('publish_at')]
#[CastNullable(ServerTimeCast::class)]
public ?Chronos $publishAt = null;
// Stored as "2025-01-01 00:00:00" in UTC
$sakura->publishAt = Chronos::wrap('2025-01-01 09:00:00', 'Asia/Tokyo');Use a real NULL for an empty date. Avoid zero dates such as 0000-00-00 00:00:00, because they are not valid values for Chronos.
INFO
When a serialized date is passed back in with its time zone, such as 2025-01-01T09:00:00+09:00, ServerTimeCast converts it to the server time zone before saving.
Date Columns
date columns can use PlainDate, a date without time. Windwalker generates it automatically with #[CastNullable(PlainDateCast::class)].
use Windwalker\Core\DateTime\PlainDate;
use Windwalker\Core\DateTime\PlainDateCast;
#[Column('birthday')]
#[CastNullable(PlainDateCast::class)]
public ?PlainDate $birthday = null;
$sakura->birthday = PlainDate::parse('2024-03-25');Time Columns
time columns can use PlainTime, a time of day without a date. It is generated with #[CastNullable(PlainTimeCast::class)].
use Windwalker\Core\DateTime\PlainTime;
use Windwalker\Core\DateTime\PlainTimeCast;
#[Column('opens_at')]
#[CastNullable(PlainTimeCast::class)]
public ?PlainTime $opensAt = null;
$sakura->opensAt = PlainTime::parse('09:30:00');INFO
PlainTimeCast accepts only values from 00:00:00 to 23:59:59.
Month and Day Values
A value that stores only a month and day, such as a yearly anniversary, can be a string in MM-DD format. This type is not generated, so you write it by hand.
#[Column('anniversary')]
public ?string $anniversary = null;To work with it as an object, use PlainMonthDay and add the cast yourself. Its toIso() method returns the MM-DD string.
use Windwalker\Core\DateTime\PlainMonthDay;
$sakura->anniversary = PlainMonthDay::parse('03-25');
echo $sakura->anniversary->toIso(); // 03-25Extending the Entity Generator
The BigInteger and BigDecimal support is built on the generator's event system. build:entity emits events while it writes each property, and a subscriber can change the result:
BuildEntityPropertyEventruns when a property is generated. It gives you thecolumn, thepropnode, and theentityMemberBuilder. Changeprop->type, add attributes, or set the default value here.BuildEntityHookEventruns whenbuild:entity -kgenerates a hook. Set$event->hookto replace the generated hook. CheckisSetandisGetto target one side.
EntityMemberBuilder provides helpers for the changes:
addUse()adds an import to the generated file.attribute()andattributeGroup()create an attribute node.createHookNode()creates a hook node from a type and an expression.
The two built-in subscribers, BigIntegerEntityMemberSubscriber and BigDecimalEntityMemberSubscriber, show the complete pattern. They are in Windwalker\Core\Generator\Subscriber.
The example below maps tinyint columns named status to a custom cast. It uses the same steps as the built-in subscribers.
// app/Generator/StatusEntityMemberSubscriber.php
namespace App\Generator;
use PhpParser\Node;
use Windwalker\Core\Generator\Event\BuildEntityPropertyEvent;
use Windwalker\Event\Attributes\EventSubscriber;
use Windwalker\Event\Attributes\ListenTo;
#[EventSubscriber]
class StatusEntityMemberSubscriber
{
#[ListenTo(BuildEntityPropertyEvent::class)]
public function buildProperty(BuildEntityPropertyEvent $event): void
{
if ($event->column->getDataType() !== 'tinyint'
|| $event->propName !== 'status') {
return;
}
$builder = $event->entityMemberBuilder;
$builder->addUse(\App\Cast\StatusCast::class);
$builder->addUse(\Windwalker\ORM\Attributes\Cast::class);
$attr = $builder->attribute(
'Cast',
new Node\Expr\ClassConstFetch(
new Node\Name('StatusCast'),
'class'
)
);
$event->prop->attrGroups[] = $builder->attributeGroup($attr);
}
}Register the subscriber in etc/app/console.config.php, the same way as the built-in ones:
// etc/app/console.config.php
'listeners' => [
\App\Generator\StatusEntityMemberSubscriber::class,
],INFO
A subscriber affects only the code that build:entity writes. Run the command again after you register it, and use -d to preview changes.