Laravel' whereNotIn'查询难度

时间:2014-08-11 20:30:40

标签: php laravel laravel-4

我试图运行以下查询并遇到此错误:

preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

当我删除' whereNotIn'部分查询工作。我知道第一个查询有效,因为我单独测试了它。我该如何解决这个错误?这是代码:

$alreadyCheckedOutDevicesQuery = DB::connection('NEWSTAFFPORTAL')->table('DeviceCheckout_checkout')->select('deviceID')->where('inBy', '=', '')->get();

$alreadyCheckedOutDevices = GlobalModel::convertDBObjectsToArray($alreadyCheckedOutDevicesQuery);

$deviceTableInformation = DB::connection('NEWSTAFFPORTAL')->table('DeviceCheckout_deviceListTestingTable')->select('deviceID', 'name', 'type', 'brand', 'model')->whereNotIn('deviceID', $alreadyCheckedOutDevices)->orderBy('name', 'ASC')->get();

2 个答案:

答案 0 :(得分:5)

尝试在子查询中执行此操作:

$info = DB::connection('NEWSTAFFPORTAL')
          ->table('DeviceCheckout_deviceListTestingTable')
          ->select('deviceID', 'name', 'type', 'brand', 'model')
          ->orderBy('name', 'asc')
          ->whereNotIn('deviceID', function ($query)
          {
              $query->from('DeviceCheckout_checkout')
                    ->select('deviceID')
                    ->where('inBy', '');
          })
          ->get();

答案 1 :(得分:4)

这将有效:

$alreadyCheckedOutDevices = DB::connection('NEWSTAFFPORTAL')
  ->table('DeviceCheckout_checkout')
  ->where('inBy', '=', '')
  ->lists('deviceID');

$deviceTableInformation = DB::connection('NEWSTAFFPORTAL')
  ->table('DeviceCheckout_deviceListTestingTable')
  ->select('deviceID', 'name', 'type', 'brand', 'model')
  ->whereNotIn('deviceID', $alreadyCheckedOutDevices)
  ->orderBy('name', 'ASC')
  ->get();

在性能方面,它应该比使用子查询更好。

简化explain

+----+--------------------+-----------------+---------+------+-------------+
| id | select_type        | type            | key     | rows | Extra       |
+----+--------------------+-----------------+---------+------+-------------+
|  1 | PRIMARY            | ALL             | NULL    |  100 | Using where |
|  2 | DEPENDENT SUBQUERY | unique_subquery | PRIMARY |    1 | Using index |
+----+--------------------+-----------------+---------+------+-------------+

+----+-------------+------+------+------+-------------+
| id | select_type | type | key  | rows | Extra       |
+----+-------------+------+------+------+-------------+
|  1 | SIMPLE      | ALL  | NULL |  100 | Using where |
+----+-------------+------+------+------+-------------+