i have 2 tables
accounts : id , title , disabled , transaction_amount_limit , transaction_count_limit
account_limits : id , account_id , transaction_amount , transaction_count , date
so each account has bunch of transaction each day ... i want to select the a account that hasn't reached its transactions limit .... current transaction for each account is stored in account_limits table
basically i want to say select account that doesn't have account_limits row or have account_limits but hasn't reached the limits account_limits.transaction_amount < accounts.transaction_amount_limit && account_limits.transaction_count < accounts.transaction_count_limit
something like
select * from `accounts`
( where not exists (select * from `account_limits` where `accounts`.`id` = `account_limits`.`account_id`)
OR
where exists (select * from `account_limits` where `accounts`.`id` = `account_limits`.`account_id` && account_limits.transaction_amount < accounts.transaction_amount_limit && account_limits.transaction_count < accounts.transaction_count_limit)
)
i have this so far
$account = Account::where('disabled' , 0 )->where(function($q){
$q->whereDoesntHave('AccountLimit')->orWhere('....') ;
})->get();
as #Flame suggested i tried
Account::whereHas('accountLimits', function($query) {
$query->where('account_limits.transaction_amount', '<', 'accounts.transaction_amount_limit')
->where('account_limits.transaction_count', '<', 'accounts.transaction_count_limit');
})->orHas('accountLimits', '=', 0);
the problem is for some reason
where('account_limits.transaction_amount', '<', 'accounts.transaction_amount_limit')
in the output will translate to
where `account_limits`.`transaction_amount` < 'accounts.transaction_amount_limit'
and query fails , there's problem with quotations
this
'accounts.transaction_amount_limit'
should be
`accounts`.`transaction_amount_limit`
Here is an example answer in the Eloquent syntax. Note that you need to add the relation:
// Account.php , your eloquent model
public function accountLimits()
{
return $this->hasMany(AccountLimit::class);
}
And for the query:
Account::whereHas('accountLimits', function($query) {
$query->where('account_limits.transaction_amount', '<', 'accounts.transaction_amount_limit')
->where('account_limits.transaction_count', '<', 'accounts.transaction_count_limit');
})->orHas('accountLimits', '=', 0);
This checks for your where-clause in the relation using whereHas, and if it is not a match, it will also add the records that match in the orHas, which finds all Accounts without accountLimits relationships.
As a straight MySQL query, something like this should work:
SELECT a.*
FROM accounts a
JOIN limits l ON l.transaction_amount < a.transaction_amount_limit AND
l.transaction_count < a.transaction_count_limit
The JOIN condition will filter out any accounts that have met or exceeded either their transaction_amount or transaction_count limits.
It is good idea for me to keep transaction_count and transaction_limit in same table (accounts).
Then you can compare this columns.
$accounts = Account::whereRaw("transaction_count < transaction_limit)->get();
Related
I have two variables $customers (that holds all the rows) and $total that holds the total rows of the query.
I usually do the following query:
$customers = Customers::select
(
'customer.id',
'customer.name',
'customer.min_tolerance',
DB::raw('(SELECT MAX(tolerance) FROM customers_tolerances WHERE customer_id = customer.id) AS tolerance')
)
->from('customers AS customer')
->whereIn('customer.id', $request->customers);
$total = $customers->count();
$customers = $customers->limit($request->limit)
->offset($request->offset)
->get();
This works great. I get all the rows limited (usually 20 per page) plus the total rows.
My problem is that I added a having clause to my query, so it looks like this now:
$customers = Customers::select
(
'customer.id',
'customer.name',
'customer.min_tolerance',
DB::raw('(SELECT MAX(tolerance) FROM customers_tolerances WHERE customer_id = customer.id) AS tolerance')
)
->from('customers AS customer')
->whereIn('customer.id', $request->customers)
->havingRaw('tolerance >= customer.min_tolerance');
And the $count stopped working as it triggers an error:
Column not found: 1054 Unknown column 'tolerance' in 'having clause'
select count(*) as aggregate from customers as customer having tolerance >= customer.min_tolerance)
So how can I use count with having clause?
Solved.
Before creating this post I tried to create a subquery, as follow:
SELECT COUNT(*) FROM (SELECT ...)
But the slowness of the query was too much, so I tried to look for answers here. The slowness was due to the lack of index in tables.
By adding ALTER TABLE customers_tolerances ADD INDEX(customer_id); I'm now able to retrieve fast the total results.
I have n users in a table and for each user, I'm saving their log-in and log-out time in a separate table. I want to get the details of the users who haven't logged-in for 2 days using Laravel eloquent.
Users table structure
id | name | email
Log table structure
id |action | user_id | created_at | updated_at
So far I have done this much:
$users = LogsData::where('action','Login')->where('created_at','<',Carbon::now()->subDays(1))->get();
But the output has users who have logged-in within 2 days also.
EDIT:
I got the query, I need to convert this into eloquent.
I solved it myself. Here is the solution:
SELECT t1.* FROM actions t1
JOIN (SELECT user_id, MAX(id) as maxid FROM actions where action = "LOGIN" GROUP BY user_id) t2
ON t1.user_id = t2.user_id and t1.id = t2.maxid
where created_at < NOW() - INTERVAL 2 DAY
If you only need to get the last data of each user, you can sort the id desc and then group by user_id to get the latest data
$users = LogsData::where('action','Login')
->whereDate('created_at','<',Carbon::today()->subDays(1))
->orderBy('id', 'DESC')
->groupBy('user_id')
->get();
to use groupBy, you have to change the strict from your config value into false. But if you don't want to change your config file, this query can help you. You just need to translate it into laravel query version
SELECT * FROM log_datas AS ld WHERE ld.action = 'Login' AND ld.id IN (SELECT MAX(id) FROM log_datas WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 DAY) GROUP_BY user_id)
You need to make a join to the logs table first, and because MySQL always seeks the path of least resistance, you need to join it the other way around: there may not exists log entries YOUNGER than 1 day.
$users = DB::from('users')
->leftJoin('logs', function ($join) {
$join->on('users.id', '=', 'logs.user_id')
->where('logs.action', '=', 'Login')
->where('logs.created_at', '>=', Carbon::now()->subDays(2));
})
->whereNull('logs.id')
->get();
Maybe try using eloquent relations
Take note of your namespaces make sure that App\LogsData for example is correct here
// in your User Model
public function logsData()
{
return $this->hasMany('App\LogsData');
}
// in your LogsData Model
public function user()
{
return $this->belongsTo('App\User');
}
public function scopeLoginActions($query)
{
return $query->where('action', 'Login');
}
Then you can access data with
User::whereHas('logsData', function ($query) {
$query->loginActions()->where('created_at', '<', now()->subDays(2));
})->get();
// and if you require the login records
User::with('logsData')->whereHas('logsData', function ($query) {
$query->loginActions()->where('created_at', '<', now()->subDays(2));
})->get();
// and if you require an individual login record
User::with(['logsData' => function($query) {
$query->loginActions()->where('created_at', '<', now()->subDays(2))->first();
})->whereHas('logsData', function ($query) {
$query->loginActions()->where('created_at', '<', now()->subDays(2));
})->get();
I have an order table and an order_details table in my system.
Relationship between order table and order details table is one to many, means One order has many order details.
Now the problem is i am trying to filter the order with the quantity of items a that are stored in order_details table.
what i doing right know trying to access with whereHas
if ($request->has('quantity') && $request->quantity != null){
$query = $query->whereHas('orderDetails',function ($q) use ($request){
$q->whereRaw('SUM(Quantity) >= '.$request->quantity);
});
}
$orders = $query->orderBy('OrderID','desc')->get();
But it throws an error
General error: 1111 Invalid use of group function (SQL: select * from `orders` where `AddedToCart` = 0 and `PaymentSucceeded` = 1 and exists (select * from `order_details` where `orders`.`OrderID` = `order_details`.`OrderID` and SUM(Quantity) >= 12) order by `OrderID` desc)
I will be vary thankful if i get the solution
To be able to use sum function you need to group by data and as I see you are trying to group them by orderID.
An approach like this might help:
$ordersIDs = DB::table('orderDetails')
->groupBy('OrderID')
->havingRaw('SUM(Quantity)', '>=', 12)
->pluck('orderID')->toArray();
$orders = DB::table('orders')
->whereIn($ordersIDs)
->get();
The above code executes two SQL queries, you can mix them easily to make one.
Hope it helps.
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.
I have been unsuccessfully trying to leftjoin and get the required data
Here is my code:
$album = Albums::->where('users_id',$user_id)
->leftJoin('photos',function($query){
$query->on('photos.albums_id','=','albums.id');
$query->where('photos.status','=',1);
//$query->limit(1);
//$query->min('photos.created_at');
})
->where('albums.status',1)->get();
The comments are some of my several trying...
I want to get only a single record from the photos table matching the foreign key album_id which was updated first and also with status 1
pls help...
I have used DB::raw() in order to achieve this
$album = Albums::select( 'albums.*',
DB::raw('(select photo from photos where albums_id = albums.id and status = 1 order by id asc limit 1) as photo') )
->where('users_id',$user_id)
->where('albums.status',1)->get();
#JarekTkaczyk 's coding was similar and displayed the same result as I needed, so a special thanks to him for his time and effort...
But comparing the execution time for the quires I stayed to mine as my above snippet
select `albums`.*, (select photo from photos where albums_id = albums.id and status = 1 order by id asc limit 1) as photo from `albums` where `users_id` = '1' and `albums`.`status` = '1'
took 520μs - 580μs
and #JarekTkaczyk 's
select `albums`.*, `p`.`photo` from `albums` left join `photos` as `p` on `p`.`albums_id` = `albums`.`id` and `p`.`created_at` = (select min(created_at) from photos where albums_id = p.albums_id) and `p`.`status` = '1' where `users_id` = '1' and `albums`.`status` = '1' group by `albums`.`id`
took 640μs - 750μs But both did the same...
You can achieve it using either leftJoin or rightJoin (but the latter would return Photo models, so probably you won't need that):
Albums::where('users_id', $user_id)
->leftJoin('photos as p', function ($q) {
$q->on('photos.albums_id', '=', 'albums.id')
->on('photos.updated_at', '=',
DB::raw('(select min(updated_at) from photos where albums_id = p.albums_id)'))
->where('photos.status', '=', 1);
})
->where('albums.status', 1)
->groupBy('albums.id')
->select('albums.*', fields from photos table that you need )
->get();
Are you trying to check for albums that have the status of '1'? If this is the case you are missing an equals sign from your final where.
Try:
->where('albums.status','=',1)->first();
Alternatively you may be able to achieve this with an 'on' instead of a 'where' inside the join function. You also don't need to split up query inside of the function and can do it as one line with the '->' :
$album = Albums::->where('users_id',$user_id)
->leftJoin('photos',function($query){
$query->on('photos.albums_id','=','albums.id')
->on('photos.status','=',1);
})
->where('albums.status','=',1)->first();
You need to make sure that you are using 'first', as it will return a single row of the first result. Get() will return an array.
As a straightforward answer which results in a single object I suggest the following query:
$album = DB::table('albums')->select('albums.*', 'photos.photo')
->join('photos', 'photos.id', '=', 'albums.id')
->where('users_id',$user_id)
->where('albums.status',1)
->first();