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();
Related
I have a table (A) that has a One to Many relation with another table (B).
I want to query Table A and eager load Table B with the Table A results - but I also want to sort Table A by a value in Table B.
I have tried using OrderBy in the query and also trying SortBy on the resultant collection but cannot get the Table A data to be sorted by the value found in Table B.
Example of what I have tried:
$query = ModelA::with("ModelB"])->get()->sortByDesc('ModelB.sortValue');
Keep in mind, I am only interested in the LATEST record from Table B. So I need to query Table A and sort by a value in the LATEST records of Table B.
How can I achieve this?
EDIT:
The below (as suggested by #ljubadr) works pretty close, but the issue is that there are many record in Table B which means that it doesn't reliably sort as it doesn't seem to sortby the latest records in Table B. Can I have the join return ONLY the latest record for each ID?
$query = ModelA::select('TableA.*')
->join('TableB', 'TableA.id', '=', 'TableB.col_id')
->groupBy('TableA.id')->orderBy('TableB.sortCol', 'desc')
->with(['x'])
->get();
EDIT 2:
#Neku80 answer has gotten me closest but it seems to not sort the column with the greatest accuracy.. I'm sorting a Decimal column and for the most part it is in order but in some places the items are out of order..
$latestTableB = ModelB::select(['TableA_id', 'sortByColumnName'], DB::raw('MAX(created_at) as created_at'))
->groupBy('TableA_id');
$query = ModelA::select('TableA.*')
->joinSub($latestTableB, 'latest_TableB', function ($join) {
$join->on('TableA.id', '=', 'latest_TableB.TableA_id');
})
->orderBy('latest_TableB.sortByColumnName')
->get();
For example, the ordering is like:
0.0437
0.0389
0.0247 <-- -1
0.025 <-- +1
0.0127
When I delete all rows except for the 'latest' rows, then it orders correctly, so it still must be ordering with old data...
I have found a solution:
ModelA::select('TableA.*', 'TableB.sortByCol as sortByCol')
->leftJoin('TableB', function ($query) {
$query->on('TableB.TableA_id', '=', 'TableA.id')
->whereRaw('TableB.id IN (select MAX(a2.id) from TableB as a2 join TableA as u2 on u2.id = a2.TableA_id group by u2.id)');
})
->orderBy('TableB.sortByCol')
->get();
Another alternative to order is like this:
$users = User::orderBy(
Company::select('name')
->whereColumn('companies.user_id', 'users.id'),
'asc'
)->get();
Here we are ordering in asc order by company name field.
In this article it is explained in detail.
You can simply execute a left join query:
ModelA::query()->leftJoin('model_b_table', 'model_a_table.primary_key', '=', 'model_b_table.foreign_key')->orderBy('model_a_table.target_column')->get();
This should work if you only need TableB's ID and created_at columns:
$latestTableB = ModelB::select('TableA_id', DB::raw('MAX(created_at) as created_at'))
->groupBy('TableA_id');
$query = ModelA::select('TableA.*')
->joinSub($latestTableB, 'latest_TableB', function ($join) {
$join->on('TableA.id', '=', 'latest_TableB.TableA_id');
})
->orderBy('latest_TableB.created_at')
->get();
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();
I have a project which has management of my investments, that is, it takes my daily statement and saves it in my project so that I can see how much it is yielding, in summary I have a table that are these values daily, I can already generate the information separated by day and it works perfectly (in fact it is a little more complex than this what I do but the basis is this);
But now it's getting bad to see when I get a very large date range for example 1 year, it lists every day, I wanted a way to group by month or week,
Thanks in advance for any help.
$rows = AtivosExtrato::select('titulo_id', DB::raw('SUM(valor_bruto_atual) AS valor'), 'data_imports.data_import as created_at')
->join('titulos','titulo_id', '=', 'titulos.id' )
->join('representantes','representante_id', '=', 'representantes.id' )
->join('data_imports','data_import_id', '=', 'data_imports.id' )
->where('user_id', Auth::user()->id)
->whereBetween('data_imports.data_import', [$request->input('start_date'), $request->input('end_date')])
->groupBy('titulos.nome_titulo')
->groupBy('data_imports.data_import')
->orderBy('data_import')
->orderBy('titulos.nome_titulo')
->get();
Briefly explaining what each eloquent information is:
AtivosExtrato: model where the daily income information is;
1) join: foreign table for the names of the titles
2) join: foreign table for the broker's name
3) join: table that saves the date of the import and relates to the id in the asset tableExtrato, it has a function to reduce the weight in the time of the searches and to gain performance.
where: limiting to the user in question
WhereBetween: limiting to date range
1) groupBy: Grouping by titles
2) groupBy: grouping by date of import
Table structure:
ativos_extrato
ativos_extratos foreign key
data_imports
Solution:
$rows = AtivosExtrato::select(
'titulo_id',
DB::raw('SUM(valor_bruto_atual) AS valor'),
'data_imports.data_import as created_at',
DB::raw('WEEK(data_imports.data_import) AS weeknumber')
)
->join('titulos','titulo_id', '=', 'titulos.id' )
->join('representantes','representante_id', '=', 'representantes.id' )
->join('data_imports','data_import_id', '=', 'data_imports.id' )
->where('user_id', Auth::user()->id)
->whereIn('ativos_extratos.data_import_id',
DataImport::Select(DB::raw('max(ID)'))
->whereBetween('data_import', [$request->input('start_date'), $request->input('end_date')])
->groupBy(db::raw('Week(data_import)')) )
->whereBetween('data_imports.data_import', [$request->input('start_date'), $request->input('end_date')])
->groupBy('titulos.nome_titulo')
->groupBy('weeknumber')
->orderBy('data_import')
->orderBy('titulos.nome_titulo')
->get();
Add DB::raw(WEEK(data_imports.data_import) AS weeknumber) and then replace ->groupBy('data_imports.data_import') with ->groupBy('weeknumber') and the same with MONTH() function if you want to group by month: add another select column DB::raw(MONTH(data_imports.data_import) AS monthnumber) and replace ->groupBy('data_imports.data_import') with ->groupBy('monthnumber'). So the whole Eloquent query with week grouping would be:
$rows = AtivosExtrato::select('titulo_id', DB::raw('SUM(valor_bruto_atual) AS valor'), 'data_imports.data_import as created_at', DB::raw('WEEK(data_imports.data_import) AS weeknumber'))
->join('titulos','titulo_id', '=', 'titulos.id' )
->join('representantes','representante_id', '=', 'representantes.id' )
->join('data_imports','data_import_id', '=', 'data_imports.id' )
->where('user_id', Auth::user()->id)
->whereBetween('data_imports.data_import', [$request->input('start_date'), $request->input('end_date')])
->groupBy('titulos.nome_titulo')
->groupBy('weeknumber')
->orderBy('data_import')
->orderBy('titulos.nome_titulo')
->get();
I am trying to get sum of amount of all users group by month.But if I add sum then query not work.It return amount log as blank array But without sum query return all logs data as monthly.
My query
$reports = $user->whereHas('groups', function ($query) use($acceptedGroup) {
$query->whereIn('groups.name',$acceptedGroup);
})->with(
array(
'amountLogs' => function($query) use($year){
$query
->select(
DB::raw('sum(amount) as total')
)
->whereYear('created_at','=', $year)
->groupBy(DB::raw("MONTH(created_at)",'user_id'))->get();
})
);
If I remove
->select(
DB::raw('sum(amount) as total')
)
Then query works
If you creating a specific select on a relationship in your query, you also need to include the foreign key to the related table (in your case, probably the users table)
->select(
'user_id',
DB::raw('sum(amount) as total')
)
This allows Eloquent to relate the records after loading from the database.
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')