php Laravel 连接查询 AS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14318205/
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
Laravel join queries AS
提问by Alex
Any way of defining an ASfor a query??
任何定义AS查询的方法?
I have tried the following:
我尝试了以下方法:
$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'));
The problem is that ['name']from categories will be replaces with the one from users. Any way of having them with different names?
问题是['name']from 类别将被替换为 from users。有什么办法让他们有不同的名字吗?
Having the aliases above... how can I create an alias where both joins return users.name?
拥有上面的别名...如何创建两个连接都返回的别名users.name?
回答by aykut
paginate()method's second parameter accepts arrayof table columns to select in the query. So this part:
paginate()方法的第二个参数接受要在查询中选择的表列数组。所以这部分:
paginate(30, array('news.title, category.name'));
must be like this:
必须是这样的:
paginate(30, array('news.title', 'category.name'));
UPDATE(after you changed the question)
更新(更改问题后)
Try this:
尝试这个:
->paginate(30, array('news.title', 'categories.name as category_name', 'users.name as user_name'));
UPDATE 2(after you changed the question, again)
更新 2 (再次更改问题后)
You can use alias on tables, too:
您也可以在表上使用别名:
$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'));
回答by justnajm
More simple and plain answer to this question is and what I was looking for that Eloquent supports aliases directly with table names or columns, for example:
对这个问题更简单明了的答案是,我一直在寻找 Eloquent 直接支持表名或列的别名,例如:
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();

