Laravel DB Query Builder traducir de mySQL

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 como 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?

preguntado el 09 de septiembre de 13 a las 21:09

Column not found. what does this error message tells ya? -

10 points for stating the obvious. :) Question rephrased for the sake of clarity. -

1 Respuestas

I would use a different approach, using inner joining 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.

Respondido el 10 de Septiembre de 13 a las 14:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.