How to Select Certain Fields in Laravel Eloquent?

后端 未结 5 835
野性不改
野性不改 2021-01-04 10:09

How to Do following Query in Laravel Eloquent?

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

I have tried followi

相关标签:
5条回答
  • 2021-01-04 10:22
    CategoryModel::wherecatType('Root')
                ->pluck('catName', 'catID', 'imgPath');
    
    0 讨论(0)
  • 2021-01-04 10:31

    Selecting multiple columns

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

    Works with Laravel 5.3 too!

    0 讨论(0)
  • 2021-01-04 10:36

    If you want to get certain columns then You can use one of the two method get() or all()

    but the syntax is different for both, get() method takes array as argument and all() method takes string or array both as argument:

    Model::all('field1','field2') with string as arguments

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

    Model::all(['field1','field2']) with array as arguments

    CategoryModel::all(['catName', 'catID', 'imgPath'])->where('catType','Root');
    

    Model::get(['field1','field2'])

    CategoryModel::get(['catName', 'catID', 'imgPath'])->where('catType','Root');
    
    0 讨论(0)
  • 2021-01-04 10:37

    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();
    
    0 讨论(0)
  • 2021-01-04 10:37

    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.

    0 讨论(0)
提交回复
热议问题