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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With