php - 如何在 Laravel 中使用两个WhereIn

标签 php mysql laravel laravel-5

我有一个简单的查询,其中 $clubs 和 $user_ids 是数组。我想在同一个查询中使用两个WhereIn。例如$clubs = array(1,2,3)和$user_id = array(25,30,40)。 DB中有一个条目,这个user_id = 25和相应的club_id = 1。我想从查询结果中列出user_id = 25。

$query = \DB::table('users_clubs')          
            ->WhereIn('user_id', $user_ids)
            ->WhereIn('club_id',$clubs)
            ->lists('user_id');

最佳答案

这就是核心中 whereIn 的代码

public function whereIn($column, $values, $boolean = 'and', $not = false)
{
    $type = $not ? 'NotIn' : 'In';

    // ... irrelevant code omitted ...

    $this->wheres[] = compact('type', 'column', 'values', 'boolean');

    $this->addBinding($values, 'where');

    return $this;
}

似乎不可能直接实现,但如果您可以以某种方式覆盖它,可能会有所帮助。

另一种方法是使用 advance where

DB::table('users_clubs')
            ->Where(function($query)
            {
                foreach( $user_ids as $user_id ){
                    $query->where('user_id', '=', $user_id);
                }

            })
            ->Where(function($query)
            {
                foreach( $clubs as $club){
                    $query->where('club_id', '=', $club);
                }
            })
            ->get();

尚未测试,但似乎经过一些修改可能会起作用。

关于php - 如何在 Laravel 中使用两个WhereIn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35425019/

相关文章:

javascript - 从 Informix 数据库返回的数据作为 php 中的未定义索引?

mysql - 在 mysql 中从 float 迁移到 decimal 的问题

php - SQL:使用计数查询返回 1

php - 在 Laravel 4 中为现有数据库创建迁移

php - Codeigniter 日历不显示正确的数据并且设置限制不起作用

php - 使用 php 将复选框值存储在数据库的不同列中(在循环中)

php - 如何更改 Symfony2 中的角色层次结构存储?

php - 如何解决执行查询时的数据库锁定问题

javascript - Laravel 中最好的图像裁剪包是什么?

php - Laravel 5 类管理员不存在