I would like to check a limit in number of user payment where a limit is set on user table.
So i have the following database structure
table user
id,name,...,pay_limit
and payment table
table payment
id, user_id, payment_ref
So i have created the following code
$query = User::query();
//other stuff
$query->leftJoin('payment','payment.user_id','=','user.id')
//stuck
Am stuck on how to check if the totals of payments on a user is not greater than the user pay_limit
How can i check the above in a query
Simple with relations. Suppose payment model is Payment and payment amount in payment_amount column
class User extends Model{
public function payments()
{
return $this->hasMany(Payment::class);
}
public function getIsOverLimitedAttribute(): bool
{
//if you check amount
return $this->payments()->sum('payment_amount') > $this->pay_limit;
//or if you check count of payments
return $this->payments()->count() > $this->pay_limit;
}
public function scopeNoOverLimited($query){
return $query->withCount('payments')->having('payments_count', '<', $this->pay_limit);
}
}
And use
if($user->isOverLimited){
//do stuff
}
Or get not over limited users:
User::noOverLimited()->get();
In terms of performance (since you want to be able to return all such users), the best approach is to store a summary column in your users table... total_payment
You can update all current users maybe via a migration file as such:
$table->integer('total_payment')->unsigned()->nullable();
DB::update("update users set total_payment = ('select count(id) from payments where user_id = id')");
Then to get all such users, you can do:
User::whereRaw('total_payment > pay_limit')->get();
Then add a PaymentObserver to increase the total_payment on new successful payments.
If you don't have access to modify the table, you can still use a scope like, but this can be performance intensive if being run all the time such as on user login without caching:
public function scopeAboveLimit($query)
{
$id = $this->id;//user id
return $query->whereRaw("pay_limit < ('select count(id) from payments where user_id = $id')");
}
Related
I have the following structure:
Charge
id
amount
created_at
..
Payment
id
amount
created_at
..
and a pivot table charge_payment, since one charge can be covered partially by multiple payments.
charge_payment
charge_id
payment_id
amount
The amount column on the pivot table defines the amount that the given Payment covers for the Charge.
And I need to get only the "paid" amount for a Payment.
I have the following models:
// Charge.php
class Charge extends Model
{
public function payments()
{
return $this->belongsToMany('App\Payment')->withPivot('amount');
}
}
// Payment.php
class Payment extends Model
{
public function charges()
{
return $this->belongsToMany('App\Charge')->withPivot('amount');
}
}
I want to be able to get only the paid amount with:
$payment = Payment::find(..);
$paid_amount = $payment->charges->sum('pivot.amount');
However, with this approach the related models are loaded from the database and I won't be needing them.
Is there a way to load only the additional pivot column without the related models?
Thank you very much!
Firstly, if one Payment can be always related only to one Charge, I would advise you to change the relationship from many-to-many to one-to-many (it will be just more correct and simpler).
Than you can simple use aggregate function (in your case withSum) which will return you only resulting values without relationship Models.
$payment = Payment::withSum('payments', 'amount')->find(..);
{{ $payment->payments_sum_amount }}
I have two tables, one is Users and the other is Loans. These have one to many relationship between them. One user can have many loans and one loan belongs to one User.
Now I want to get the user from the list of loans.
Loan::where('user_id', $user)->get()
This give me repeated array of sample user associated to the multiple loans. But I want to get only a single record, like many loans associate to one user.
I assume you already set up relationships between User & Loan Models
// App\User
public function loans() {
return $this->hasMany('App\Loan');
}
// App\Loan
public function user() {
return $this->belongsTo('App\User');
}
Get user from the list of loans
$user = Loan::where('user_id', $id)->first()->user;
// eager loading version
$loansWithUsers = Loan::with('user')->where('user_id', $id)->get();
Loans associate to one user
$loans = User::findOrFail($id)->loans;
// eager loading version
$userWithLoans = User::with('loans')->findOrFail($id);
For what I understand in your question, you want to get the user together with it's loan right ? Your query should like this.
$user_loans = User::with('loans')->where('id', $user_id)->get();
Get the user informations from loan table
Loan::where('user_id', $user_id)->with('user')->get()
Ge the users from loans table depends on brach id
Loan::where('branch_id', $branch_id)->with('user')->get();
Im new to laravel db query. I have problem when want to query.
I have two table customer and history. In history it have few column which are customer_id, activity (purchase,buyback), product_type(gold,silver) and quantity. Currently I want to retrieve balance for each of customer. To get balance, purchase - buyback.
-> customer_id | gold_balance | silver_balance
Here I attach two part of table and code to be review.
Thanks in advance.
You should create a hasMany relationship between Customer and History (maybe called histories) and create a custom attribute that loops through histories and add/subtract amount.
Something like this (not tested):
class Customer {
public function histories() {
return $this->hasMany(History::class);
}
public function getBalanceAttribute() {
return $this->histories->reduce(function($total, $current) {
$grossAmount = $current->amount * $current->quantity;
return $current->activity === 'purchase' ? $total - grossAmount : $total + grossAmount;
}, 0;
}
}
I have 3 tables
entry (
id,
title,
other_stuff)
entry_award (
id,
award_id,
entry_id)
award (
id,
name,
type)
I am trying to create a laravel query which lets me get all the entries that have awards, and order them by award.type ASC
$Entries = Entry::with('award')
->whereHas('award', function ($query) {
$query->orderBy('award.award_id','ASC');
})->paginate(20);
But this doesn't work.
This is the sql version of it
SELECT DISTINCT entry.*
FROM entry, award, entry_award
WHERE entry.id = entry_award.entry_id
AND award.id = entry_award.award_id
ORDER BY award.type ASC;
Now I tried to just use the raw sql for it, but the problem seems to be that laravel does not then recognize the result as Entry models/objects. And i need to get other Entry relations later on in the html via blade.
So how can I either make a query-builder query that gets me all entries that have awards and orders them by award.type value
or use the raw sql but have Laravel see it as an array of Entry
objects instead of just an array of JSON values.
class Entry extends Model {
public function entry_award(){
return $this->belongsToMany('App\Award', 'entry_award');
}
}
class Award extends Model {
public function entries() {
return $this->belongsToMany('App\Entry', 'entry_award');
}
}
I have a list of Groups with Users. Groups has a property maximum_users. Users can register in a Group only if they have a free place (If count of registered users in that Group does not exceed maximum_users property of that Group).
How can I select only Groups with free places where Users can register?
I need to paginate the results.
I can filter groups after selecting them with this condition:
$group->maximum_users >= $group->users()->count()
but in this case pagination doesn't work.
Table structure:
groups
id - integer
maximum_users - integer
users
id - integer
group_id - integer
Models:
class Group extends Model
{
public function users()
{
return $this->hasMany('App\Models\User');
}
}
class User extends Model
{
public function group()
{
return $this->belongsTo('App\Models\Group');
}
}
How can I select only Groups with free places where Users can register?
I need to paginate the results.
i would strongly recommend to use a pivot table, unless user can only be in one group, with pivot table something like this should work:
Group::whereRaw('(SELECT COUNT(*)
FROM groups_users
WHERE group_id = group.id) < group.maximum_users')
->paginate(15);
With your current structure
Group::whereRaw('(SELECT COUNT(*)
FROM users
WHERE group_id = groups.id) < groups.maximum_users')
->paginate(15);