Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel give data Type bit/byte in migration

Is there any database similiar to bit (byte) in laravel, could not find any in the documentation. (https://laravel.com/docs/5.1/migrations).

I try to do something like:

00000001 -> stands for something lets say playstation

00000010 -> stands for xbox

00000011 -> stands for both above
like image 704
Alex Oxilg Avatar asked Oct 30 '22 06:10

Alex Oxilg


1 Answers

Instead of trying to use the BIT datatype, which would be a bit of a hassle to work with, you can just use an integer and bitwise operators instead, assuming you don't need more than 32 options for one field (bigint = 8 bytes = 32 bits).

As a very simple example, imagine you create the following enum class:

class Bitmask {
    const ATARI       = 1 << 0; // 00000001 (1)
    const NES         = 1 << 1; // 00000010 (2)
    const SNES        = 1 << 2; // 00000100 (4)
    const SEGA        = 1 << 3; // 00001000 (8)
    const PLAYSTATION = 1 << 4; // 00010000 (16)
    const XBOX        = 1 << 5; // 00100000 (32)
}

To set the field, all you need to do is add the bitmasks together (in this configuration, ORing (|) them is the same). If a user has an NES and a PLAYSTATION:

$user->systems = Bitmask::NES + Bitmask::PLAYSTATION;

To query, you would use the bitwise operators. So, if you wanted the users that have SEGAs:

User::where('systems', '&', Bitmask::SEGA)->get();

If you wanted the users that have PLAYSTATIONs or XBOXes:

User::where('systems', '&', Bitmask::PLAYSTATION | Bitmask::XBOX)->get();

The & operator will perform a bitwise AND operation between the integer field and the integer you pass in. If any of the bits match up, the & operator will return a value > 0, and the where clause will be truthy. If none of the bits match up, the & operator will return 0 and the where clause will be false.

like image 178
patricus Avatar answered Nov 15 '22 07:11

patricus