Laravel:whereIn不使用给定数组作为参数

时间:2015-05-05 04:10:41

标签: laravel query-builder

这两行代码看起来完全一样。

   1: $q = \App\User::whereIn('id',[1,2,3]);

   2: $users = DB::table('users')->whereIn('id', array(1, 2, 3));

但结果却不同。

第1行不会选择任何结果。它的收藏是空的。 第2行可以选择其用户ID在给定范围内的正确用户。

有人能说出理由吗?

这是命令行的更多输出。

>>> $users = DB::table('users')->whereIn('id', array(1, 2, 3));
=> <Illuminate\Database\Query\Builder #00000000201a36590000000030994e20> {
       aggregate: null,
       columns: null,
       distinct: false,
       from: "users",
       joins: null,
       wheres: [
           [
               "type"    => "In",
               "column"  => "id",
               "values"  => [
                   1,
                   2,
                   3
               ],
               "boolean" => "and"
           ]
       ],
       groups: null,
       havings: null,
       orders: null,
       limit: null,
       offset: null,
       unions: null,
       unionLimit: null,
       unionOffset: null,
       unionOrders: null,
       lock: null
   }

>>> $q = \App\User::whereIn('id',[1,2,3]);
=> <Illuminate\Database\Eloquent\Builder #0000000018080e2500000000179a03c5> {}

这是User.php

<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

        use Authenticatable, CanResetPassword;

        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'users';

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = ['name', 'email', 'password'];

        /**
         * The attributes excluded from the model's JSON form.
         *
         * @var array
         */
        protected $hidden = ['password', 'remember_token'];

}

这是“get()”输出。

>>> \App\User::whereIn('id',[1,2,3])->get();
=> <Illuminate\Database\Eloquent\Collection #000000007833eb04000000000d6d8434> {}
>>> DB::table('users')->whereIn('id', array(1, 2, 3))->get();
=> [
       <stdClass #000000007833eb1e000000000d6d8434> {
           id: 1,
           name: "test",
           email: ****,
           password: ****,
           remember_token: null,
           created_at: "2015-03-23 03:32:32",
           updated_at: "2015-03-30 03:13:34",        
       }

1 个答案:

答案 0 :(得分:1)

两者都应该相同,但您应该使用get运行查询:

$q = \App\User::whereIn('id',[1,2,3])->get();

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();