Laravel join queries AS

Alex picture Alex · Jan 14, 2013 · Viewed 60.1k times · Source

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 ?

Answer

aykut picture aykut · Jan 14, 2013

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