Laravel selectRaw with joined table data - php

I am using the following to sum a total column:
$hive_count = Hive::where('active','true')
->groupBy('hive_type_id')
->selectRaw('sum(total) as sum, hive_type_id')
->pluck('sum','hive_type_id');
But rather than using the hive_type_id for the array key, I would like to access the hive_type name from the hive_types table (column 'name'). I have tried hive_type_id.name but this did not work.
Models: Hive & HiveType
Thanks for your help.

I would like to access the hive_type name from the hive_types table (column 'name').
You've to join the table hive_types in your query so you can access the name :
$hive_count = DB::table('hives')
->where('active','true')
->join('hive_types', 'hives.hive_type_id', '=', 'hive_types.id')
->groupBy('hive_type_id','hive_types.name')
->selectRaw('sum(total) as sum, hive_types.name as name')
->pluck('sum','name');

Related

getting joined tables id instead main table in blade

Do I need to specify main table's name in order to get that tables id instead joined table's id , My codes are (from controller ) :
public function RegistrationEditView(Request $r,$id){
$data=DB::table('bootcamp_users')->leftJoin('countries_detailed', function($join) {
$join->on('countries_detailed.id', '=', 'bootcamp_users.country_id');
})->where('bootcamp_users.id',$id)->first();
$course_lists=DB::table('course_languages')->get();
$bootcamps=DB::table('bootcamp_users')->get();
return view('admin.registeredBootcamp.edit',compact('data','course_lists','bootcamps'));
}
That's because the default SELECT behaviour of Laravel's query builder is SELECT * so any column sharing the same name in a joined table will overwrite the original selected table's columns: that's why you see countries_detailed.id instead of bootcamp_users.id.
I suggest specifying a custom select statement to only select needed columns from both tables, for example:
$data = DB::table('bootcamp_users')
->select(['bootcamp_users.id', /* Add all needed columns here */])
->leftJoin('countries_detailed', function($join) {
$join->on('countries_detailed.id', '=', 'bootcamp_users.country_id');
})->where('bootcamp_users.id',$id)->first();

How to select all the values from a table except the values which are in foreign table?

I have three tables:tbl_borrower, tbl_clientandtbl_guarantor
tbl_Client:
id|name|address|email|
tbl_Guarantor:
id|clientid(fk)|Guaranteed_date|borrower_id(fk from borrower table)
I want to retrieve all the values of client table except the values which are present in guarantor table in the controller of Laravel 5.5.
Once you have the models and relationships set up, you should just do:
Client::doesntHave('guarantor')->get()
https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-absence
If you're using the query builder, it would be:
$clients = DB::table('tbl_clients')
->join('tbl_guarantor', 'tbl_clients.id', '=', 'tbl_guarantor.clientid')
->select('tbl_clients.*')
->whereNull('tbl_guarantor.clientid')
->get();
https://laravel.com/docs/5.5/queries
With the premise of using a left join and testing for NULL on the 2nd table id based on this answer. https://stackoverflow.com/a/4076157/3585500
Try this :
DB::table('tbl_Client')
->groupBy('tbl_Client.id')
->leftjoin('tbl_Guarantor', 'tbl_Client.id', '=', 'tbl_Guarantor.clientid')
->get([
'tbl_Client.*'
]);

Not able to fetch data from the second table on join query in laravel eloquent

I was trying to fetch a category list using left join (on the same table) to get the parent category as well.
The query looks like
SELECT categories.`cat_id`, categories.`cat_name`, categories.`cat_desc`, categories.`parent_id`, categories.`created_at`,cat2.cat_name FROM `categories` JOIN categories cat2 ON categories.parent_id = cat2.cat_id
So on Laravel eloquent i wrote
$categoryModel::select('categories.cat_id', 'categories.cat_name', 'categories.cat_desc', 'categories.parent_id', 'categories.created_at','cat2.cat_name')
->leftJoin('categories AS cat2','categories.parent_id', '=' , 'cat2.cat_id')
->get();
Unfortunately, the result comes with only the first table columns
[{"cat_id":1,"cat_name":"Camera","cat_desc":null,"parent_id":3,"created_at":null},{"cat_id":2,"cat_name":"Camera","cat_desc":null,"parent_id":3,"created_at":null},{"cat_id":3,"cat_name":null,"cat_desc":null,"parent_id":null,"created_at":null},{"cat_id":4,"cat_name":null,"cat_desc":null,"parent_id":null,"created_at":null},{"cat_id":5,"cat_name":"CCTV","cat_desc":null,"parent_id":4,"created_at":null},{"cat_id":6,"cat_name":"CCTV","cat_desc":null,"parent_id":4,"created_at":null}]
Thanks in advance. :)
Here both table columns have same name, so you need to use alias for second table's column as of this please below change in your query like 'cat2.cat_name as c_name'
$categoryModel::select('categories.cat_id', 'categories.cat_name', 'categories.cat_desc', 'categories.parent_id', 'categories.created_at','cat2.cat_name as c_name' )
->leftJoin('categories AS cat2','categories.parent_id', '=' , 'cat2.cat_id')
->get();
It worked this way, I gave the alias for each column.
$categoryModel::select('cat1.cat_id as catId', 'cat1.cat_name as catName', 'cat1.cat_desc as catDesc', 'cat1.parent_id as parId', 'cat1.created_at as cAt','cat2.cat_name as parCatName')
->from('categories as cat1')
->leftJoin('categories AS cat2','cat1.parent_id', '=' , 'cat2.cat_id')
->get();

Laravel 4: Count relationship within whereHas

I have 2 tables as below:
Subscription table have a entrance_limit column, and it has a hasMany('Attendance') relationship. The entrance_limit column will actually limit the number of rows in Attendance. For example, if the entrance_limit value is 10, then we only can create 10 rows in Attendance.
Attendance table has a belongsTo('Subscription') relationship.
How do I get the list of Subscription that have total number of Attendance less than the entrance_limit value?
Subscription::whereHas('attendances', function($q) {
## something like this
$q->count() < subscription->entrance_limit
})
Model your query has below
Subscription::whereHas('attendances', function($q) {
$q->where('entrance_limit','>',$q->count());
})
Finally able to get it working with the following:
Subscription::whereRaw('
(select count(*) from `attendances` where `attendances`.`subscription_id` = `subscriptions`.`id`) < `subscriptions`.`entrance_limit`
');

Column Name Conflict on Laravel 4 Fluent Query Builder

I have a query like this:
$users = DB::table('users')->join('user_roles','users.role_id','=','user_roles.id')->get();
and a table that has a column id (users.id) and another table that has columns id and user_id (user_roles.id & user_roles.user_id),
but the problem is.. what is being returned on $user->id is the user_roles.id instead of the users.id column.. how do i fix this so that what i get is not the role id but the user id instead..
thanks!
Found it!
using ->select('users.*', 'user_roles.role_name') i was able to remove user_roles.id from the returned values and thus eliminating the conflict.
Here is the final query:
$users = DB::table('users')->join('user_roles','users.role_id','=','user_roles.id')->select('users.*', 'user_roles.role_name')->get();
The better way to do this is using 'as':
$users = DB::table('users')->join('user_roles','users.role_id','=','user_roles.id')->get(array('users.*', '**user_roles.id as user_roles_id**', 'user_roles.*'));

Categories