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

[Proposal] Add schema method storedAsNotNull and virtualAsNotNull #1211

Closed
mpyw opened this issue Jun 9, 2018 · 2 comments
Closed

[Proposal] Add schema method storedAsNotNull and virtualAsNotNull #1211

mpyw opened this issue Jun 9, 2018 · 2 comments

Comments

@mpyw
Copy link

mpyw commented Jun 9, 2018

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.

@mpyw
Copy link
Author

mpyw commented Jun 9, 2018

Options:

  • Backward Compatible: Add storedAsNotNull and virtualAsNotNull
  • Breaking Change: Make storedAs and virtualAs not null by default and accept nullable call

@mpyw mpyw changed the title Add schema method storedAsNotNull and virtualAsNotNull [Proposal] Add schema method storedAsNotNull and virtualAsNotNull Jun 9, 2018
@mpyw mpyw closed this as completed Oct 10, 2019
@mpyw mpyw reopened this Oct 10, 2019
@driesvints
Copy link
Member

A pr for this was merged.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants