Laravel加入查询AS [英] Laravel join queries AS
本文介绍了Laravel加入查询AS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为查询定义 AS
的任何方式?
Any way of defining an AS
for a query??
我尝试了以下方法:
$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
中的用户.可以用不同的名称来命名它们吗?
The problem is that ['name']
from categories will be replaces with the one from users
. Any way of having them with different names?
具有上面的别名...如何创建两个连接都返回 users.name
的别名?
Having the aliases above... how can I create an alias where both joins return users.name
?
推荐答案
paginate()
方法的第二个参数接受表列的 array 以便在查询中进行选择.所以这部分:
paginate()
method's second parameter accepts array of table columns to select in the query. So this part:
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 (再次更改问题后)
您也可以在表上使用别名:
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'));
这篇关于Laravel加入查询AS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文