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
?
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.
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.
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With