I am trying to select a calculated column based on columns in related tables.
This is the equivalent in SQL
SELECT
*,
(p.weight * p.fineness * f.fixam / 31.1035) as buy_gram
FROM
products p, fixes f, metals m
WHERE
p.metal_id = m.id AND
f.metal_id = m.id AND
f.currency_id = :cid
This is my attempt so far using Laravel Query Builder.
$products = Product::select(
['*',DB::raw('weight * fineness * fixes.fixam / 31.1035 as buy_gram')])
->with(array(
'metal',
'metal.fixes.currency',
'metal.fixes' => function($query) use ($currency_id){
$query->where('currency_id', '=', $currency_id);
}))->get();
return View::make('admin.products.index')->with('products', $products);
I am faced with an error message saying:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fixes.fixam' in 'field list' (SQL: select *, weight * fineness * fixes.fixam as buy_gram from `products`) (Bindings: array ( ))
I have also tried other combinations of fixes.fixam
such as metal.fixes.fixam
, metals.fixes.fixam
Question 1: How do I query this foreign table to perform the calculation using laravel query builder? Question 2: Is there some kind of console / log file that I can output the generated sql for my laravel queries to?
I would use a different approach, using inner join
ing tables. Something like this:
DB::table('products')
->join('metals','products.metal_id','=','metals.id','inner')
->join('fixes','fixes.metal_id','=','metals.id','inner')
->where('fixes.currency_id',':cid')
->select(DB::raw('products.*, (products.weight * products.fineness * fixes.fixam / 31.1035) as buy_gram'))
->get();
To achieve the last query:
$queries = DB::getQueryLog();
$last_query = end($queries);
You can also use a profiler to see all the queries and more information. juy/profiler is the one I'm using.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.