Eloquent:在关系上调用 Where

Posted

技术标签:

【中文标题】Eloquent:在关系上调用 Where【英文标题】:Eloquent: Calling Where on a relation 【发布时间】: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();

【问题讨论】:

【参考方案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() 部分和一个 ;

以上是关于Eloquent:在关系上调用 Where的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 关系上的枢轴关系 (Eloquent)

在 Eloquent 关系上使用 first()

Laravel 5 Eloquent在多个级别上向JSON添加关系

Laravel Eloquent 所有与关系

优化 Eloquent 关系检索

Laravel Eloquent 在 belongsToMany 关系上返回一个空集合