Laravel join queries AS

你离开我真会死。 提交于 2020-11-30 06:15:04

问题


Any way of defining an AS for a query??

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?

Having the aliases above... how can I create an alias where both joins return users.name ?


回答1:


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

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)

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



回答2:


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:

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


来源:https://stackoverflow.com/questions/14318205/laravel-join-queries-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!