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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17713730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:19:13  来源:igfitidea点击:

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

phplaravellaravel-4eloquent

提问by prograhammer

Lets say we are using Laravel's query builder:

假设我们正在使用 Laravel 的查询构建器:

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

I'm looking for an equivalent to this SQL:

我正在寻找与此 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?

当我必须输入大量选择和 wheres(或者通常我也将别名包含在选择的列别名中,并在结果数组中使用它)时,这将特别有用。没有任何表别名,我的打字量要多得多,而且一切都变得不那么可读了。在laravel 文档中找不到答案,有什么想法吗?

回答by peterm

Laravel supports aliases on tables and columns with AS. Try

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

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

Let's see it in action with an awesome tinkertool

让我们用一个很棒的tinker工具来看看它的实际效果

$ 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'
//   )
// )

回答by AMIB

To use aliases on eloquent models modify your code like this:

要在 eloquent 模型上使用别名,请像这样修改您的代码:

Item
    ::from( 'items as items_alias' )
    ->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
    ->select( DB::raw( 'items_alias.*' ) )
    ->get();

This will automatically add table prefix to table names and returns an instance of Itemsmodel. not a bare query result. Adding DB::rawprevents laravel from adding table prefixes to aliases.

这将自动为表名添加表前缀并返回Items模型的实例。不是一个简单的查询结果。添加DB::raw可防止 Laravel 向别名添加表前缀。

回答by Koushik Das

Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.

下面是如何做到这一点。我将举一个加入的例子,以便对某人变得非常清楚。

$products = DB::table('products AS pr')
        ->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
        ->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
        ->orderBy('pr.id', 'desc')
        ->get();

Hope this helps.

希望这可以帮助。

回答by muinh

To use in Eloquent. Add on top of your model

在 Eloquent 中使用。添加到您的模型之上

protected $table = 'table_name as alias'

protected $table = 'table_name as alias'

//table_name should be exact as in your database

//table_name 应该与您的数据库中的完全相同

..then use in your query like

..然后在您的查询中使用

ModelName::query()->select(alias.id, alias.name)

ModelName::query()->select(alias.id, alias.name)

回答by Carlos h Gonzalez

You can use less code, writing this:

您可以使用更少的代码,这样写:

    $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name'));

And of course if you want to select more fields, just write a "," and add more:

当然,如果您想选择更多字段,只需写一个“,”并添加更多:

 $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));

This is very practical when you use a joins complex query

这在您使用连接复杂查询时非常实用

回答by Ahmed Gamal

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed()then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

与AMIB答案相同,对于软删除错误“未知列'table_alias.deleted_at'”,只需添加->withTrashed()然后自己处理->whereRaw('items_alias.deleted_at IS NULL')