問題描述
假設我們正在使用 Laravel 的查詢構建器:
$users = DB::table('really_long_table_name')-> 選擇('really_long_table_name.id')->get();
我正在尋找與此 SQL 等效的語句:
really_long_table_name AS short_name
當我必須輸入大量選擇和 wheres(或者通常我在選擇的列別名中也包含別名,并且它在結果數組中使用)時,這將特別有用.如果沒有任何表別名,我就需要打更多的字,而且一切都變得不那么可讀了.在 laravel 文檔中找不到答案,有什么想法嗎?
Laravel 支持使用 AS
為表和列設置別名.試試
$users = DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
讓我們用一個很棒的 tinker
工具來看看它的作用
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?
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' // ) // )
這篇關于如何在 Laravel Eloquent 查詢(或使用查詢生成器)中為表添加別名?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!