如何在Laravel雄辩查询(或使用Query Builder)中别名表? [英] How to alias a table in Laravel Eloquent queries (or using Query Builder)?

查看:307
本文介绍了如何在Laravel雄辩查询(或使用Query Builder)中别名表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们正在使用Laravel的查询生成器:

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

我正在寻找与此SQL相当的价格:

  really_long_table_name AS short_name 

有帮助的时候,我必须键入很多的选择和wheres(或通常我将select的列别名中包含别名,并将其用于结果数组)。没有任何表别名,对我来说有更多的打字,一切都变得很少可读。没有找到答案在laravel docs,任何想法?

解决方案

Laravel支持表和列上的别名为 AS 。尝试

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

让我们看看它在一个非常棒的修补程序工具

 
$ php artisan tinker
[1]> Schema :: create('really_long_table_name',function($ table) {$表 - >增量( '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();
//数组(
// 0 => object(stdClass)(
//'uid'=>'1'
//)
//)


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雄辩查询(或使用Query Builder)中别名表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆