Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel join queries AS

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 ?

like image 945
Alex Avatar asked Jan 14 '13 12:01

Alex


People also ask

How can write join query in laravel 8?

If you want to join two or multiple tables in laravel then you can use laravel eloquent join(), left join(), right join(), cross join(). And another option to join two or multiple table, you can use laravel eloquent relationships instead of laravel join.

How use inner join in laravel?

You can pass 5th argument to the join() function which will specify type of join (default is "inner"). If you're using Eloquent and have "League" model then you can use join on the model too: $leagues = League::select('league_name') ->join('countries', 'countries. country_id', '=', 'leagues.


1 Answers

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')); 
like image 144
aykut Avatar answered Nov 07 '22 02:11

aykut