How to alias a table in Laravel Eloquent queries (or using Query Builder)?

PhpLaravelLaravel 4Eloquent

Php Problem Overview


Lets say we are using Laravel's query builder:

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

I'm looking for an equivalent to this SQL:

really_long_table_name AS short_name

This would be especially helpful when I have to type a lot of selects and wheres (or typically I include the alias in the column alias of the select as well, and it get's used in the result array). Without any table aliases there is a lot more typing for me and everything becomes a lot less readable. Can't find the answer in the laravel docs, any ideas?

Php Solutions


Solution 1 - Php

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'
//   )
// )

Solution 2 - Php

To use aliases on eloquent models modify your code like this:

Item
    ::from( 'items as items_alias' )
    ->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
    ->select( DB::raw( 'items_alias.*' ) )
    ->get();

This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result. Adding DB::raw prevents laravel from adding table prefixes to aliases.

Solution 3 - Php

Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.

$products = DB::table('products AS pr')
        ->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
        ->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
        ->orderBy('pr.id', 'desc')
        ->get();

Hope this helps.

Solution 4 - Php

To use in Eloquent. Add on top of your model

protected $table = 'table_name as alias'

>//table_name should be exact as in your database

..then use in your query like

ModelName::query()->select(alias.id, alias.name)

Solution 5 - Php

You can use less code, writing this:

    $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name'));

And of course if you want to select more fields, just write a "," and add more:

 $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));

This is very practical when you use a joins complex query

Solution 6 - Php

I have tried all these options and none works for me. Then I had found something in the Laravel documentation that really works.

You could try this:

DB::table('table_one as t1')
    ->select(
        't1.field_id as id','t2.field_on_t2 as field'
     )->join('table_two as t2', function ($join) {
        $join->on('t1.field_id ', '=', 't2.field_id');
    })->get()

Solution 7 - Php

Also note that you can pass an alias as the second parameter of the table method when using the DB facade:

$users = DB::table('really_long_table_name', 'short_name')
           ->select('short_name.id')
           ->get();

Not sure if this feature came with a specific version of Laravel or if it has always been baked in.

Solution 8 - Php

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprograhammerView Question on Stackoverflow
Solution 1 - PhppetermView Answer on Stackoverflow
Solution 2 - PhpAMIBView Answer on Stackoverflow
Solution 3 - PhpKoushik DasView Answer on Stackoverflow
Solution 4 - PhpmuinhView Answer on Stackoverflow
Solution 5 - PhpCarlos h GonzalezView Answer on Stackoverflow
Solution 6 - PhpKenier Cumba BuenoView Answer on Stackoverflow
Solution 7 - PhptheDudeView Answer on Stackoverflow
Solution 8 - PhpAhmed GamalView Answer on Stackoverflow