You do have a model setup, right?
Oct 28, 2022
6
Level 1
sub queries and query builder
is there a way to write a sub query and use query builder (needed to add 'if' clauses not included below for simplicity)
Here is the query I am trying to build in query builder:
select license, itemtype, varieties_string, DATE(date), scale_string, packagetags_string, derivedtable.weightvaluesum, derivedtable.plantcountavg, (derivedtable.weightvaluesum/derivedtable.plantcountavg) as answer
from(
select license, itemtype, varieties_string, DATE(date), scale_string, packagetags_string, Sum (weightvalue) AS weightvaluesum, Avg (plantcount) AS plantcountavg
from weightrecords
where farm_string = 'My Produce, LLC'
Group By license, itemtype, varieties_string, DATE(date), scale_string, packagetags_string
order by license, itemtype, varieties_string, DATE(date), scale_string, packagetags_string
) AS derivedtable
Here is the inner query:
$query = weightrecords::query();
$query = $query->selectRaw('license, itemtype, varieties_string, DATE(date), scale_string, packagetags_string, SUM (weightvalue) AS weightvaluesum, AVG (plantcount) AS plantcountavg');
$query = $query->where('farm_string', '=', 'My Produce, LLC');
$query = $query->groupByRaw('license, itemtype, varieties_string, DATE(date), scale_string, packagetags_string');
$query = $query->orderByRaw('license, itemtype, varieties_string, DATE(date), scale_string, packagetags_string');
$query = $query->get();
but how do I build the outer query? It does not seem to map to something like https://laravel.com/docs/9.x/queries#subquery-where-clauses
Level 10
I think the issue is the subquery needs an alias, which sould be the 2nd parameter of the from() method
$yield_per_license = DB::query()->from($sub)
That's why your query ends up being "select... from (select....) as \"\", which is invalid
Please or to participate in this conversation.