如何在Laravel Eloquent查询中(或使用查询生成器)对表进行别名?

问题描述 投票:104回答:6

让我们说我们正在使用Laravel的查询构建器:

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

我正在寻找这个SQL的等价物:

really_long_table_name AS short_name

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

php laravel laravel-4 eloquent
6个回答
173
投票

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

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

让我们用一个很棒的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'
//   )
// )

54
投票

要在雄辩的模型上使用别名,请修改您的代码,如下所示:

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();

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


3
投票

这是人们可以做到的。我将举一个加入的例子,以便它变得非常清楚。

$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 family_name', 'pf.id as family')
        ->orderBy('pr.id', 'desc')
        ->get();

希望这可以帮助。


2
投票

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

protected $table = 'table_name as alias'

// table_name应该与数据库中的一样精确

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

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


1
投票

你可以使用更少的代码,写下这个:

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

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

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

当您使用联接复杂查询时,这非常实用


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.