Skip to content
This repository was archived by the owner on Jul 16, 2021. It is now read-only.
This repository was archived by the owner on Jul 16, 2021. It is now read-only.

[Proposal] Add schema method storedAsNotNull and virtualAsNotNull #1211

Closed
@mpyw

Description

@mpyw

Currently ->storedAs() and ->virtualAs() always make them nullable.

https://github.com/laravel/framework/blob/1cbb54e9da52d66bc09e181c34520df283bf46cd/src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php#L892-L897

But making generated columns non-nullable provides robust and flexible constraints.

Example

Goals

  • We have members table and plans table
    • members.role takes one of owner guest subscriber
    • members.plan_id has value only when members.role is subscriber
  • We also need to sort members in owner guest subscriber order.

Code

$table
->unsignedTinyInteger('sort_priority')
->storedAsNotNull("
    CASE WHEN role = 'owner' AND plan_id IS NULL THEN 1
         WHEN role = 'guest' AND plan_id IS NULL THEN 2
         WHEN role = 'subscriber' AND plan_id IS NOT NULL THEN 3
         ELSE NULL
    END
")
->index();

members.sort_priority allows us making fast sorting ORDER BY sort_priority, id ensuring strong consistency.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions