Viewed   88 times

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 )

 Answers

1

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();
Wednesday, October 19, 2022
 
3

Laravel supports aliases on tables and columns with AS. Try

$users = DB::table('really_long_table_name AS t')
           ->select('t.id AS uid')
           ->get();

Let's see it in action with an awesome tinker tool

$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
//   0 => object(stdClass)(
//     'uid' => '1'
//   )
// )
Friday, October 28, 2022
2

This can be resolved by specifying the specific column names desired from the specific table like so:

$c = Customer::leftJoin('orders', function($join) {
      $join->on('customers.id', '=', 'orders.customer_id');
    })
    ->whereNull('orders.customer_id')
    ->first([
        'customers.id',
        'customers.first_name',
        'customers.last_name',
        'customers.email',
        'customers.phone',
        'customers.address1',
        'customers.address2',
        'customers.city',
        'customers.state',
        'customers.county',
        'customers.district',
        'customers.postal_code',
        'customers.country'
    ]);
Tuesday, August 9, 2022
 
2
$query->whereBetween('age', [$ageFrom, $ageTo]);

Look here: http://laravel.com/docs/4.2/queries#selects

Still holds true for Laravel 5: https://laravel.com/docs/5.8/queries#where-clauses

Thursday, September 8, 2022
 
5

You can do it like this:

Table::select('name','surname')->where('id', 1)->get();
Tuesday, October 25, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :