【问题标题】:laravel 5.4 bitwise operations not working as expected (Eloquent)laravel 5.4 按位运算未按预期工作(雄辩)
【发布时间】:2018-03-05 23:58:45
【问题描述】:

这让我很难过。我正在尝试使用按位运算符 & 基于 productmask 字段过滤 $ages=Ages::all(); (代码应该是不言自明的)

我试过了

  @foreach($ages->where('productmask', '&', 2) as $option)      

和

  @foreach($ages->filter(function($i){return ((int)($i->productmask & 2)); }) as $option)

和

  @foreach($ages->filter(function($i){return ((int)($i->productmask & 2) == 2); })->values() as $option)

当 productmask = 3 时没有任何工作,但当 productmask 正好为 2 时工作。

我在这里有什么选择(不是双关语)?为什么这不起作用?

如果我执行\DB::whereRaw,我很确定它会起作用(因为我可以对 Db 运行它并且它起作用并且我得到 2 和 3 条目):

SELECT * from ages WHERE productmask&2

但是在这里它绕过了流利并在视图中访问数据库?不好的形式。

任何使用位掩码的人都遇到过这种情况吗?

提前致谢。

【问题讨论】:

    标签: laravel bitwise-operators fluent laravel-eloquent bitmask


    【解决方案1】:

    从source这里建议

    where() 接受 3 个参数,列名,运算符和值 进行比较。

    运算符可以是以下之一:'='、''、'='、 ''、'!='、'喜欢'、'不喜欢'、'介于'、'喜欢'

    但是我发现了一些您可能需要查看的内容here。 这将帮助您解决问题。

    要进一步挖掘see PHP documentation,请阅读此SO post

    就你的问题而言

    像这样使用你的查询

    $ages->whereRaw('(productmask & 2)')
    

    【讨论】:

    • 是的,我看过了,但我不想为了缓解 Eloquent 看似简单的数学问题而添加新包和实现新字段类型。或者至少以他们的方式我正在尝试使用它。从 vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php protected $operators = [ '=', '', '=', '', '!=', 'like', 'like binary', 'not like', 'between', 'ilike', '&', '|', '^', '>', ' rlike', 'regexp', 'not regexp', '~', '~*', '!~', '!~*', '类似于', '不相似', ];
    • 我试过 whereRaw。该方法似乎只在类 (Ages:whereRaw()) 上可用。当我尝试在$ages=Ages::all(); 的结果上使用它时,我得到了一个找不到的方法。 $ages->whereRaw() 失败。
    【解决方案2】:

    嗯,我不知道为什么我必须这样做,但我是这样做的:

    @foreach($locations->filter(function($i){if (decbin($i->productmask) & 16) return $i; }) as $option)      
    

    基本上,我必须在集合的字段值 ($ages->productmask) 上使用 decbin(),以便正确解析比较。

    现在工作!希望这对某人有所帮助。

    【讨论】:

    • 很高兴你解决了这个问题 :)
    • 一旦您有资格接受答案,请接受答案以结束您的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2015-05-11
    • 2019-06-20
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多