Laravel 关系中的按位与条件 (Eloquent ORM)

Яро*_*лин 4 php orm laravel eloquent

我正在尝试在用户(模型)与组模型之间创建专门的关系。在我正在使用的模式中,组有一个类型属性,它是位掩码,其中每个位定义组的特定特征。

例如,我们可能有一个组:

name: New York
type: 33554436 (1<<25 | 1<<24)
Run Code Online (Sandbox Code Playgroud)

使用普通 SQL,我可以通过查询获取感兴趣的组:

name: New York
type: 33554436 (1<<25 | 1<<24)
Run Code Online (Sandbox Code Playgroud)

为了方便起见,我希望在用户模型中定义这种关系,并且有:

<?php

class UserModel extends Illuminate\Database\Eloquent\Model
{

    public function visitedCities()
    {
        return $this->belongsToMany(
            GroupModel::class,
            'foobar_group_member',
            'user_id',
            'group_id')
          ->with([ 'type' => function ($belongsToMany) {
              $belongsToMany->where('type', '&', 
                    GroupModel::CITY_TYPE,
                    GroupModel::CITY_TYPE)
          }])
        ;
    }
}
Run Code Online (Sandbox Code Playgroud)

本质上,我试图将上面 SQL 查询中的 where 条件添加到 join 语句(关系)中。你知道怎么做吗?我需要扩展 Eloquent\Relation 类吗?

Vic*_*son 5

您可以用来whereRaw执行原始 where 子句。

Eloquent 不支持比likeor=和标准内容更奇特的 where 子句。我建议你看看文档

我的情况你可能想使用类似的东西:

$belongsToMany->whereRaw('(type & 1<<25) != 0')
Run Code Online (Sandbox Code Playgroud)

并将其添加到您的 select 子句中。

如果你想调试 SQL,你可以使用:

DB::enableQueryLog();
//Execute Eloquent select
dd(DB::getQueryLog());
Run Code Online (Sandbox Code Playgroud)

这样您还可以看到,如果您将位掩码之类的内容放入 where 子句的中间部分,它将被替换为=