Laravel STDDEV with LIMIT - php

I'm trying to get the AVG() and the STDDEV_SAMP() on subset of data using Laravel.
So I've tried
//Data from which I want to calculate the AVG and STDDEV_SAMP()
//Limit the query to certain values
$subquery = TableAModel::join('TableB','TableA.TableB_id','=','TableB.id')
->select('Factor1')
->whereraw('conditionA <= 10')
->orderBy('DateTimeCode', 'desc')
->take('5')
->toSql();
//My aggregate functions
$aggregates = 'AVG(TableA.Factor1) as Factor1,
STDDEV_SAMP(TableA.Factor1) as Factor1_SD';
//My final query that should return the average and SD
$AVG_SD = \DB::table(\DB::raw(" ($subquery) as sub "))->select(\DB::raw("$aggregates"))->first()->toArray();
//it should return something like array([Factor1] => The_average, [Factor1_SD] => The_SD)
However, it throws me "Column not found: 1054 Unknown column 'TableA.Factor1' in 'field list'". If I try to select('*'), it throws me "Duplicate columns id".

I don't really have any experience with this but, it looks to me like your creating a view and from that view you want to find the STD and AVG of Factor1. But you say AVG(TableA.Factor1) as Factor1, I don't think TableA would be the table name for DB::table(\DB::raw(" ($subquery) as sub ")) so its not finding Factor1 because its can't find the table. would the table not be called sub.
I have no idea if this is the case or not, but hope it helps, also would've left a comment but I don't have the rep yet :(.

Related

Laravel filtering - get the last created entry from the DB which has a specific ID

For this data (from a table called status_student):
I want to do some filtering. This table is a pivot table and I want to return a record from a base table only if the latest created object has a specific status_id.
For example, if I filter for status_id = 1, I shouldn't get any object for those two rows.
Here's my query for filtering:
$query = Student::whereHas('statusuri', function($q) use ($status) {
$q->orderBy('status_student.data_sfarsit', 'desc')->where('status_id', '=', $status);
});
statusuri From Student:
public function statusuri()
{
return $this->belongsToMany(Status::class, 'status_student')
->withPivot('id', 'data_inceput', 'data_sfarsit', 'document', 'status_id', 'stare_stagiu_id')
->withTimestamps();
}
My query works, but it returns an object if I filter for a status_id of 1 and of 6 too. I only want to return an object for filtering with status_id = 6 (because that is the latest status).
I tried modifying my query like this:
$query = Student::whereHas('statusuri', function($q) use ($status) {
$q->orderBy('status_student.data_sfarsit', 'desc')->first()->where('status_id', '=', $status);
});
but then it didn't work, and I think I know the reason.
first() returns an instance of another type (after an inner join, basically), which doesn't have a status_id. So I shouldn't use it this way. Also, it returns an object, not a Query Builder instance anymore.
The error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'students.id' in 'where clause' (SQL: select * from `statusuri` inner join `status_student` on `statusuri`.`id` = `status_student`.`status_id` where `students`.`id` = `status_student`.`student_id` order by `status_student`.`data_sfarsit` desc limit 1)
So, how can I make that query filter my latest created DB row with a specific status_id?
Thanks.
//Example:
For student_id = 1 as in the picture:
if status_id = 1:
query returns nothing
if status_id = 6:
query returns the student
Explanation:
$status_id is provided through a HTML form, and I want to return that specific student if the last status known is equal to this $status_id.
My approach was filtering with latest(id) so I get the latest entry on the first row, then getting the first entry, then doing a where clause on the status_id. But it doesn't work because first() returns an object, not a QueryBuilder anymore.

Laravel using eloquent Count with Having

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.

Need help building query laravel 5.2

I'm trying to get rings from the database. but only filter is the homepage is 1 or 0.
I only need the rows where homepage is 1.
This is what i tried
$ringen = RingKoppelCategory::with('ringen')->get()->where('homepage', '=' , 1);
returns null
And when i put the ->get() at the end of the query builder it checks the ringkoppelcategory table for a homepage which is not what i want it to do.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'homepage' in 'where clause' (SQL: select * from `ringkoppelcategory` where `homepage` = 1
I need to get the rings relationship from the ringkoppelcategory, but only the rings where the homepage is 1.
You need to use a function to pass along a where within your with.
$ringen = RingKoppelCategory::with(['ringen' => function ($query) {
$query->where('homepage', '=' , 1);
}])->get();
More information is found in the documentation
I think you need to use the following query
$ringen = RingKoppelCategory::whereHas('ringen', function ($query) {
$query->where('homepage', '=', 1);
})->get();
Check Querying Relationship Existence section at documentation

Yii2 query all get value in join

I have an database with tablenames like this: tbl_accessoires_1, tbl_accessoires_2 etc. In my main table is a column that gives me the number for the table I have to join. But how do I get this value if I use ->all().
This is my query:
$query = (new Query())
->select([
'a.id id',
'a.soort soort',
])
->from('auto_new a')
->leftJoin('tbl_accessoires_--soort-- acc', 'acc.id = a.id')
->all();
So the a.soort in the select must be at the --soort--
Is there any way to do this?
If I only get one car it is possible because I could get the soort value before this query. but how do I do this when I want to get all cars
So because it's not possible in my situation I've just made a new query to get the options. This will do for now because I don't really need the options when I get all cars.

Laravel 5.1 whereNotNull with join not working (returning all data)

I am trying to Select all non empty columns in 'user' table where column name is 'review'.
$applications = DB::table('users')
->join('applications', 'user.update_id', '=', 'applications.id')
->whereNotNull('users.review')
->select('user.id', 'user.rating', 'user.appid', 'user.review', 'applications.title', 'applications.price', 'applications.icon_uri')
->orderBy('user.id','asc')
->paginate(20);
$applications->setPath('');
return $applications;
But return data includes all information of both 'user.review' empty and not empty as well.
I feel there is no effect of whereNotNull() and i found no error in the statement.
I tried moving ->whereNotNull('user.review') this line top and bottom result is same.
I tried even by removing select and orderBy but returns same data.
$applications = DB::table('users')
->join('applications', 'user.update_id', '=', 'applications.id')
->whereNotNull('users.review')
->paginate(20);
$applications->setPath('');
return $applications;
Is there any way to make it work?
if your table is users you are missing an s in the table name, you should write
->whereNotNull('users.review')
same case in the join with the field update_id, otherwise you have to change the table name in the table method

Categories