Laravel: select students who do not have payment made in the month - php

I want to make a list of students who did not make payment in the current month, or never made a payment.
it is possible to do with a single query builder, or eloquent function?
With the code below I can do exactly the opposite of what I want :/
$indebted = DB::table('students')->where('students.active',1)
->leftJoin('payments', 'students.id', '=', 'payments.user_id')
->whereMonth('payments.created_at','=', $today->month)
->get();

I don't know what value you are passing here.
$today->month
Instead of this $today->month you have to pass exact month here
Please try this
$indebted = DB::table('students')->where('students.active',1)
->leftJoin('payments', 'students.id', '=', 'payments.user_id')
->whereMonth('payments.created_at','=', 06)
->get();

Here is the students ids who made payments in Current month and year
$payments= DB::table('payments')
->whereMonth('created_at',date('m'))
->whereYear('created_at', date('Y'))
->pluck('user_id')->all();
use whereNotIn('id',[students ids who made payments])
$students = DB::table('students')
->whereNotIn('id',$payments)
->get();

You can use Raw SQL in this kind of situation
I am assuming you are using mysql database
$sql=SELECT * from students s LEFT JOIN payments p ON s.id=p.user_id
WHERE s.active=1 AND (p.created_at is NULL or MONTH(MAX(p.created_at) < MONTH(CURRENT_DATE())) )
$students = DB::connection('mysql')->select( DB::raw(" $sql"));
foreach($students as $aStudent){
...
....
}

you can get student who do not have payments made in this month
$students = App\student::whereDoesntHave('payments', function (Builder $query) {
$query->whereMonth('payments.created_at',$today->month);
})->where('active',1)->get();

Related

Using multi where queries Laravel relationships

I have two tables (Table1, Table2).
I want to print the sum of the records whose properties match Table1 in Table2 while listing the Table1 table.
My two tables contain very large records, performance is important to me.
// Model -> relationships
public function cars()
{
return $this->hasMany('App\Models\Table2', 'list_id', 'list_id');
}
// Controller
$table1 = Table1::with('cars' => function($query){
$query->where('table2.color','=', 'table1.color')
$query->where('table2.year','=', 'table1.year')
}])
->get();
I'm adding the sample database pictures:
Thank you.
First, add below use statement to the top of your controller:
use DB;
Now, If you only want to get the records amount, you can do this:
$amount = DB::table('table1')
->join('table2', function($join){
$join->on('table1.color', '=', 'table2.color');
$join->on('table1.year', '=', 'table2.year');
})->count();
But if you want to get the list of the table1 records, you can change the query a bit like below:
$records = DB::table('table1')
->select('table1.*')
->join('table2', function($join){
$join->on('table1.color', '=', 'table2.color');
$join->on('table1.year', '=', 'table2.year');
})->count();
Please follow Laravel's official guide on this topic:
https://laravel.com/docs/8.x/queries#advanced-join-clauses
Use join to merge the two tables read more about join here https://www.w3schools.com/sql/sql_join.asp

Sum of column in where clause in laravel eloquent

I have a FamilyMember model and a SubscriptionCharge model, SubscriptionCharge store charges of multiple months of each family member.
I have to select members whos sum of charges greater than a specific amount.
$members=FamilyMember::whereHas('subscription_charge', function ($qq) {
$qq->where(); // how to check sum of column 'amount' in where
})->get();
How to check the sum of column 'amount' in a where condition
Based on your comment, Updated Answer
$memeber = FamilyMember::query()
->join(DB::raw('("SELECT subscription_charge.family_member_id, SUM(subscription_charge.amount) as total_charges FROM subscription_charge GROUP BY subscription_charge.family_member_id HAVING SUM(subscription_charge.amount) >
AMOUNT_YOU_WANT") as sub_table'), function($join) {
$join->on('sub_table.family_member_id', '=', 'family_member.id');
})->get();
Note: Not tested
I think you might be able to do something like this. (I'm at the airport so unable to test it.)
$members=FamilyMember->join(DB::raw('(SELECT family_member_id, SUM(amount) AS sum_of_charges
FROM subscription_charge
WHERE family_member_id = x
GROUP BY family_member_id
// (or HAVING family_member_id = x ?)
) charges'),
function($join)
{
$join->on('FamilyMember.id', '=', 'charges.family_member_id');
})
->select(
'FamilyMember.id',
'charges.sum_of_charges'
)
->where('sum_of_charges', '>', 'Y')
})->get();

Codeigniter : Join 2 tables based on where condition

I have to select data from two tables for APIs.
There are two tables garage_services, and garages. I receive garage_sevices id.
Garage_services table is like this
id | garage_id | service _id
Now from this table I select row based on service_id from here I have to select garage_id and get details about garage from garage table
$garages = $this->db
->select('*')
->from('garage_services')
->join('garage', 'garage_services.id=garage.id')
->where($where)
->get();
Above is the query I came up with, I don't know if its correct. as I am not sure about $where as well.
Please help me with this
Here I have written the query for your solution.
$garages = $this->db->from('garage_services as gs, garages as g')
->where('g.id', $garage_service_id, FALSE)
->get();
Here $garage_service_id is the variable that passed in function argument as you have written you in your question.
Try this
->select('*')
->from('garage_services as t1')
->join('garage as t2', 't1.garage_id = t2.id')
->where('t1.id', $service _id)
->get();
As per the detail is given in the question your query look correct and for the where condition:
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table1.col1 = table2.col1');
$this->db->where('table1.col1', 2);
$query = $this->db->get();

Laravel query with max and group by

I need to create a select query in Laravel 5.1 which I will have no problems creating via regular SQL and I am wondering if you could help me to write it in Laravel.
I created this query that gets all Users that have a truck, trailer and delivery_date equals a particular date (comes from $week_array). It is working, but it is missing some components
$RS = $this->instance->user()
->with(['driver.delivery' => function($query) use ($week_array) {
$query->where('delivery_date', [Carbon\Carbon::parse($week_array['date'])->toDateTimeString()]);
}])
->with(['driver.trailer', 'driver.truck', 'driver.trailer.trailerType'])->get();
I need to exclude those drivers that have MAX delivery date which equals or greater than selected delivery date in the query above. This is the normal query that I need to plug-in to laravel.
In other words, I need to convert the following query (simplified) to Laravel:
SELECT
*
FROM
USERS
INNER JOIN
DRIVERS ON DRIVERS.user_id = USERS.id
INNER JOIN
DELIVERIES ON DELIVERIES.driver_id = DRIVERS.id
WHERE
1 = 1
AND DELIVERIES.driver_id NOT IN (SELECT
driver_id
FROM
DELIVERIES
GROUP BY driver_id
HAVING MAX(delivery_date) >= '2016-05-10')
You're looking for whereHas. Try:
$date = Carbon\Carbon::parse($week_array['date'])->toDateTimeString();
$RS = $this->instance->user()
->with(['driver.delivery' => function($query) use ($date) {
$query->where('delivery_date', [$date]);
}])
->with(['driver.trailer', 'driver.truck', 'driver.trailer.trailerType'])
->whereHas('driver.delivery', function($query) use ($date) {
return $query->where('delivery_date', '>', $date);
}, '=', 0)
->get();
Also try validating the query looks right by replacing ->get() with ->toSql() and using the dd helper function.

Laravel Query Builder - sum() method issue

I'm new to laravel and I have some issues with the query builder.
The query I would like to build is this one:
SELECT SUM(transactions.amount)
FROM transactions
JOIN categories
ON transactions.category_id == categories.id
WHERE categories.kind == "1"
I tried building this but it isn't working and I can't figure out where I am wrong.
$purchases = DB::table('transactions')->sum('transactions.amount')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->select('transactions.amount')
->get();
I would like to get all the transactions that have the attribute "kind" equal to 1 and save it in a variable.
Here's the db structure:
transactions(id, name, amount, category_id)
categories(id, name, kind)
You don't need to use select() or get() when using the aggregate method as sum:
$purchases = DB::table('transactions')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->sum('transactions.amount');
Read more: http://laravel.com/docs/5.0/queries#aggregates
If one needs to select SUM of a column along with a normal selection of other columns, you can sum select that column using DB::raw method:
DB::table('table_name')
->select('column_str_1', 'column_str_2', DB::raw('SUM(column_int_1) AS sum_of_1'))
->get();
You can get some of any column in Laravel query builder/Eloquent as below.
$data=Model::where('user_id','=',$id)->sum('movement');
return $data;
You may add any condition to your record.
Thanks
MyModel::where('user_id', $_some_id)->sum('amount')

Categories