如何在 Laravel Eloquent 查询(或使用查询生成器)中为表添加别名?

How to alias a table in Laravel Eloquent queries (or using Query Builder)?(如何在 Laravel Eloquent 查询(或使用查询生成器)中为表添加别名?)
本文介绍了如何在 Laravel Eloquent 查询(或使用查询生成器)中为表添加别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

假设我们正在使用 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 工具来看看它的作用

<前>$ 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 => 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 Eloquent 查询(或使用查询生成器)中为表添加别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)