【问题标题】:Laravel join queries ASLaravel 连接查询 AS
【发布时间】:2012-12-28 09:34:13
【问题描述】:

为查询定义AS 的任何方式??

我尝试了以下方法:

$data = News::order_by('news.id', 'desc')
    ->join('categories', 'news.category_id', '=', 'categories.id')
    ->left_join('users', 'news.user_id', '=', 'users.id') // ['created_by']
    ->left_join('users', 'news.modified_by', '=', 'users.id') // ['modified_by']
    ->paginate(30, array('news.title', 'categories.name as categories', 'users.name as username'));

问题是类别中的['name'] 将被users 中的替换。有什么方法可以让它们具有不同的名称?

拥有上面的别名...如何创建两个连接都返回 users.name 的别名?

【问题讨论】:

    标签: php mysql pagination laravel eloquent


    【解决方案1】:

    paginate() 方法的第二个参数接受 array 的表列以在查询中选择。所以这部分:

    paginate(30, array('news.title, category.name'));
    

    必须是这样的:

    paginate(30, array('news.title', 'category.name'));
    

    更新 (在您更改问题后)

    试试这个:

    ->paginate(30, array('news.title', 'categories.name as category_name', 'users.name as user_name'));
    

    更新 2 (在您更改问题后,再次)

    您也可以在表格上使用别名:

    $data = News::order_by('news.id', 'desc')
        ->join('categories', 'news.category_id', '=', 'categories.id')
        ->join('users as u1', 'news.user_id', '=', 'u1.id') // ['created_by']
        ->join('users as u2', 'news.modified_by', '=', 'u2.id') // ['modified_by']
        ->paginate(30, array('news.title', 'categories.name as categories', 'u1.name as creater_username', 'u2.name as modifier_username'));
    

    【讨论】:

      【解决方案2】:

      这个问题的更简单明了的答案是,我一直在寻找的是 Eloquent 直接支持带有表名或列的别名,例如:

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

      【讨论】:

        猜你喜欢
        • 2014-02-19
        • 1970-01-01
        • 2020-04-10
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-11
        • 1970-01-01
        相关资源
        最近更新 更多