How to alias a table in Laravel Eloquent queries (or using Query Builder)?(如何在 Laravel Eloquent 查询(或使用查询生成器)中为表起别名?)
问题描述
假设我们正在使用 Laravel 的查询构建器:
$users = DB::table('really_long_table_name')->select('really_long_table_name.id')->get();我正在寻找与此 SQL 等效的方法:
really_long_table_name AS short_name当我必须输入大量选择和位置时,这将特别有用(或者通常我在选择的列别名中也包含别名,并且它在结果数组中使用).没有任何表格别名,我的打字量会增加很多,而且一切都变得不那么可读了.在 laravel 文档中找不到答案,有什么想法吗?
解决方案Laravel 支持
AS表和列的别名.试试$users = DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();让我们用一个很棒的
<上一页>$ php工匠修补匠[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});//空值[2] > DB::table('really_long_table_name')->insert(['id' => null]);//真的[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();//大批(//0 => 对象(stdClass)(//'uid' => '1'//)//)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 查询(或使用查询生成器)中为表起别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Laravel Eloquent 查询(或使用查询生成器)中为表起别名?
				
        
 
            
        - Laravel 仓库 2022-01-01
 - 从 PHP 中的输入表单获取日期 2022-01-01
 - 带有通配符的 Laravel 验证器 2021-01-01
 - 正确分离 PHP 中的逻辑/样式 2021-01-01
 - 没有作曲家的 PSR4 自动加载 2022-01-01
 - PHP Count 布尔数组中真值的数量 2021-01-01
 - 如何定位 php.ini 文件 (xampp) 2022-01-01
 - Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
 - SoapClient 设置自定义 HTTP Header 2021-01-01
 - Mod使用GET变量将子域重写为PHP 2021-01-01
 
				
				
				
				