首页 文章

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

提问于
浏览
92

让我们说我们正在使用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中找不到答案,有什么想法吗?

5 回答

  • 149

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

  • 2

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

    protected $table = 'table_name as alias'

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

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

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

  • 41

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

    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 model的实例 . 不是一个简单的查询结果 . 添加 DB::raw 可防止laravel将表前缀添加到别名 .

  • 0

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

    $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

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

相关问题