I was looking through Laravel's source code and I've found a lot of SQL operators for Eloquent and I was wondering what are some of them and how can they be used.
I haven't managed to find any documentation unfortunately.
Here's the operators I've found in vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
:
protected $operators = [
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'like binary', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
'~', '~*', '!~', '!~*', 'similar to',
'not similar to',
];
And there's a bunch of them I don't understand. For example: &
, |
, ^
, <<
, >>
, ~
, ~*
, !~
, !~*
.
Can anyone show me an example of how they can be used?
Thanks
Just like other commenters have mentioned, those are bitwise operators. PHP's bitwise operators are documented here: http://php.net/manual/en/language.operators.bitwise.php
Examples
&
is a bitwise AND operator.
A bitwise AND takes two equal-length binary representations and performs the logical AND operation on each pair of the corresponding bits, by multiplying them. Thus, if both bits in the compared position are 1, the bit in the resulting binary representation is 1 (1 × 1 = 1); otherwise, the result is 0 (1 × 0 = 0 and 0 × 0 = 0)
10 & 10 = 10 (all decimal representation). How? 10 is 1010 binary.
1010
and 1010
--------
1010
Notice that the result is 1 only when both top and bottom number in the same column are 1.
PHP's way of writing that:
<?php
echo 10 & 10;
?>
Result: 10
What's the practical use for it? Let's take an example: There are 4 sets of double doors. Both doors have to open at the same time for a person to pass through. Open door is given number 1. Closed door is given number 2.
1010
means first door is open, second is closed, third is open, fourth is closed. When all doors are closed, they would look like this:
0000 <-- first set of doors
0000 <-- second set of doors
To allow someone to pass through left-most door, doors should be like this:
0001
0001
That's all fine, but there's a faster way to annotate that. Bitwise operator &. We do & between both doors and get a result of 1. So if data is stored as 1, we know that left-most doors were open.
To open left-most door, the combination would have to be:
1000
1000
Result of bitwise operator is decimal 8. Use calculator like the one on miniwebtool to run some math.
On the flip side, as the doors open and close all day, one could record when both doors of any of the 4 sets of doors were open. It's just a long-winded answer to perhaps a simple question.
Posted this as a comment on the original question:
They're bitwise operators. Here is what they do (this is the javascript implementation).
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