How to Alias Tables in Laravel Eloquent and Query Builder?

Linda Hamilton
Release: 2024-10-20 09:22:02
Original
677 people have browsed it

How to Alias Tables in Laravel Eloquent and Query Builder?

Aliasing 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>
Copy after login

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>
Copy after login

Using AS with Eloquent

<code class="php">$users = App\User::from('really_long_table_name AS t')
           ->select('t.id AS uid')
           ->get();</code>
Copy after login

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'
//   )
// )
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!