Laravel join queries AS

2022-08-30 13:49:05

定义查询的任何方法??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'));

问题是 from 类别将被 替换为 来自 的类别。有什么方法可以让他们有不同的名字?['name']users

具有上述别名...如何创建两个联接都返回的别名?users.name


答案 1

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

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

推荐