【问题标题】:Eloquent: Calling Where on a relationEloquent:在关系上调用 Where
【发布时间】:2013-09-09 04:10:38
【问题描述】:

我有以下 Eloquent ORM 查询。

$products2 = Product::with('metal', 'metal.fixes', 'metal.fixes.currency')
    ->where('metal_id', '=', 1)
    ->get()->toArray();

此查询的输出如下:

http://pastebin.com/JnDi7swv

我希望进一步缩小查询范围,只显示fixes.currency_id = 1 的产品。

$products2 = Product::with('metal', 'metal.fixes', 'metal.fixes.currency')
    ->where('metal_id', '=', 1)
    ->where('metal.fixes.currency_id', '=', 1)
    ->get()->toArray();

有人可以帮我解决这个问题吗,因为我收到以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'metal.fixes.currency_id' 
in 'where clause' (SQL: select * from `products` where `metal_id` = ? 
and `metal`.`fixes`.`currency_id` = ?) (Bindings: array ( 0 => 1, 1 => 1, ))

在 Rob Gordijn 的帮助下解决了:

$products2 = Product::with(array(
    'metal', 
    'metal.fixes.currency', 
    'metal.fixes' => function($query){
        $query->where('currency_id', '=', 1);
     }))
        ->where('common', '=', 1)
        ->where('metal_id', '=', 1)
        ->get()->toArray();

【问题讨论】:

    标签: mysql orm laravel laravel-4 eloquent


    【解决方案1】:

    您正在寻找“急切负载约束”:http://laravel.com/docs/eloquent#querying-relations

    <?php
    $products2 = Product::with(array('metal', 'metal.fixes', 'metal.fixes.currency' => function($query){
        $query->where('currency_id', '=', 1);
    }))
    ->where('metal_id', '=', 1)
    ->get()->toArray();
    

    【讨论】:

    • 谢谢。非常有帮助。我已经在我编辑的问题中稍微调整了您的解决方案并修复了语法错误等。
    • NP,我也修正了我的答案。错过了 array() 部分和一个 ;
    猜你喜欢
    • 2018-04-20
    • 1970-01-01
    • 2022-01-15
    • 2021-08-22
    • 2014-07-21
    • 2015-07-05
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多