How to Select Certain Fields in Laravel Eloquent?

2019-02-13 22:00发布

How to Do following Query in Laravel Eloquent?

SELECT catID, catName, imgPath FROM categories WHERE catType = "Root"

I have tried following

CategoryModel::where('catType', '=', 'Root')
                ->lists('catName', 'catID', 'imgPath');

but its return only two fields.

Array ( [7] => Category 1 )

4条回答
姐就是有狂的资本
2楼-- · 2019-02-13 22:13

From laravel version 5.3^ lists() is deprecated and function pluck() is used instead.

pluck() returns a collection and if you need a simple array just prepend ->toArray() to it.

查看更多
Rolldiameter
3楼-- · 2019-02-13 22:14

lists() turns the resulting collection into an array with key value. You can only have two database columns in there. Otherwise you have to use select() but then you will get a collection of models not just an array.

$categories = CategoryModel::select('catID', 'catName', 'imgPath')
                           ->where('catType', '=', 'Root')
                           ->get();
查看更多
贼婆χ
4楼-- · 2019-02-13 22:25
CategoryModel::wherecatType('Root')
            ->pluck('catName', 'catID', 'imgPath');
查看更多
ゆ 、 Hurt°
5楼-- · 2019-02-13 22:36

Selecting multiple columns

CategoryModel::get(['catName', 'catID', 'imgPath']);

Works with Laravel 5.3 too!

查看更多
登录 后发表回答