查询Laravel表时如何获得相同的结果数组

时间:2019-03-29 07:19:32

标签: php laravel

使用laravel模型内置的laravel时,将返回结果数组的列表。但是当查询同一个表时会得到不同的对象。请检查以下代码-如何获得相同的结果集?

$users = User::all();

Illuminate\Support\Collection Object
(
    [items:protected] => Array
    (
        [0] => stdClass Object
        (
            [id] => 10
            [email] => amirtha@gmail.com
        )

        [1] => stdClass Object
        (
            [id] => 12
            [email] => renjith@123.com

        )
    )

但是当使用如下所示的sql查询时:

$result = DB::table('users as u')
            ->select('u.id','u.email','u.role','u.created_at')
            ->join('roles as r','r.id','=','u.role')
            ->where('u.role', '!=',  1 )
            ->orderBy('u.name','asc')
            ->get();
            print_r($result);

我得到:

Illuminate\Database\Eloquent\Collection Object
(
    [items:protected] => Array
    (
        [0] => App\User Object
        (
            [fillable:protected] => Array
            (
                [0] => name
                [1] => email
                [2] => password
                [3] => lastname
                [4] => mobile
                [5] => role
            )

            [hidden:protected] => Array
            (
                [0] => password
                [1] => remember_token
            )

            [casts:protected] => Array
            (
                 [email_verified_at] => datetime
            )

            [connection:protected] => mysql
            [table:protected] => users
            [primaryKey:protected] => id
            [keyType:protected] => int
            [incrementing] => 1
            [with:protected] => Array
            (
            )

            [withCount:protected] => Array
            (
            )

            [perPage:protected] => 15
            [exists] => 1
            [wasRecentlyCreated] => 
            [attributes:protected] => Array
            (
                [id] => 1
                [name] => amritha
                [email] => amritha@gmail.com
            )

2 个答案:

答案 0 :(得分:2)

我认为您的问题是当您想使用表别名时如何处理?

 $result =  User::query()->from('User as u')
            ->select('u.id','u.email','u.role','u.created_at')
            ->join('roles as r','r.id','=','u.role')
            ->where('u.role', '!=',  1 )
            ->orderBy('u.name','asc')
            ->get();

答案 1 :(得分:0)

此查询与“ SELECT * FROM USERS”相同
    $ users = User :: all();

这与先前的查询不同

$result = DB::table('users as u')
->select('u.id','u.email','u.role','u.created_at')
->join('roles as r','r.id','=','u.role')
->where('u.role', '!=',  1 )
->orderBy('u.name','asc')
->get();
print_r($result);