简体   繁体   English

Laravel DB查询生成器从MySQL转换

[英]Laravel DB Query Builder translate from mySQL

I am trying to select a calculated column based on columns in related tables. 我正在尝试根据相关表中的列选择一个计算列。

This is the equivalent in SQL 这在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. 到目前为止,这是我使用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 我还尝试了fixes.fixam其他组合,例如metal.fixes.fixammetals.fixes.fixam

Question 1: How do I query this foreign table to perform the calculation using laravel query builder? 问题1:如何使用laravel查询生成器查询此外部表以执行计算? Question 2: Is there some kind of console / log file that I can output the generated sql for my laravel queries to? 问题2:是否存在某种控制台/日志文件,我可以将生成的sql输出到laravel查询中?

I would use a different approach, using inner join ing tables. 我会使用另一种方法,即使用inner join联接表。 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. juy / profiler是我正在使用的工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM