33

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 ?

Alex
  • 7,538
  • 23
  • 84
  • 152

2 Answers2

93

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'));
aykut
  • 2,984
  • 24
  • 26
4

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();
justnajm
  • 4,422
  • 6
  • 36
  • 56