【问题标题】:Laravel DB Query Builder translate from mySQLLaravel DB 查询生成器从 mySQL 翻译
【发布时间】:2013-09-13 09:53:17
【问题描述】:

我正在尝试根据相关表中的列选择计算列。

这是 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

这是我迄今为止使用 Laravel 查询生成器的尝试。

    $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);

我遇到一条错误消息:

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 ( ))

我也尝试过fixes.fixam的其他组合如metal.fixes.fixammetals.fixes.fixam

问题 1:如何使用 laravel 查询生成器查询这个外部表来执行计算? 问题 2:是否有某种控制台/日志文件可以输出我的 laravel 查询生成的 sql 到?

【问题讨论】:

  • Column not found。这个错误信息告诉你什么?
  • 10 分用于陈述显而易见的事情。 :) 为了清楚起见,重新表述了问题。

标签: php orm laravel eloquent query-builder


【解决方案1】:

我会使用不同的方法,使用inner joining 表。像这样的:

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();

实现最后一个查询:

$queries = DB::getQueryLog();
$last_query = end($queries);

您还可以使用分析器查看所有查询和更多信息。 juy/profiler 是我正在使用的。

【讨论】:

    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多