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 )
Select specific columns with Laravel Eloquent To get all of the columns from the users table, we would use the following: $user = User::where('username', 'bobbyiliev')->get(); However, if you wanted to get only a specific column, you could pass it as an argument to the get() method.
Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array. Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.
Subqueries allow you to run nested queries within another database query. This can be a powerful way to retrieve ancillary model data, without making any additional database queries, when it's not possible to do via a relationship.
Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all.
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();
Selecting multiple columns
CategoryModel::get(['catName', 'catID', 'imgPath']);
Works with Laravel 5.3 too!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With