Home > Article > Backend Development > How to Alias Tables in Laravel Eloquent and Query Builder?
In Laravel's query builder, you may encounter scenarios where renaming a table alias would enhance code readability and reduce typing effort. Suppose you have a table with a lengthy name like 'really_long_table_name'.
The SQL syntax for aliasing a table is:
<code class="sql">really_long_table_name AS short_name</code>
To achieve the same in Laravel's query builder, follow these steps:
Using AS with Query Builder
<code class="php">$users = DB::table('really_long_table_name AS t') ->select('t.id AS uid') ->get();</code>
Using AS with Eloquent
<code class="php">$users = App\User::from('really_long_table_name AS t') ->select('t.id AS uid') ->get();</code>
Example Usage
Let's use Tinker to demonstrate the functionality:
$ 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' // ) // )
By aliasing tables and columns, you can simplify your queries, making them more readable and concise.
The above is the detailed content of How to Alias Tables in Laravel Eloquent and Query Builder?. For more information, please follow other related articles on the PHP Chinese website!