【问题标题】:How do I query a deep relationship in laravel and filter parents by children?如何查询laravel中的深层关系并按孩子过滤父母?
【发布时间】:2019-08-08 15:55:14
【问题描述】:

例如,如果一个品类有很多产品有很多 sku,我如何获得所有 sku 价格大于 10 的产品?

这将返回所有类别,但只附加了预期的 skus,我只想要已说 skus 的类别。

$category = new Category();
$category->with(array('products', 'products.skus' => function ($query) {
    $query->where('price', '>', 10);
}))->get();

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您正在寻找的是whereHas()。你也可以直接写with(array('products.skus'))而不用products

    $category = new Category();
    $categories = $category->with(array('products', 'products.skus' => function ($query) {
            $query->where('price', '>', 10);
        }))
        ->whereHas('products.skus', function($query){
            $query->where('price', '>', 10);
        })->get();
    

    withwhereHas 两者都需要,但您可以通过将闭包放在变量中来稍微简化代码:

    $priceGreaterTen = function($query){
        $query->where('price', '>', 10);
    };
    
    $category = new Category();
    $categories = $category->with(array('products', 'products.skus' => $priceGreaterTen))
                           ->whereHas('products.skus', $priceGreaterTen)
                           ->get();
    

    【讨论】:

    • 我不断收到Call to undefined method Illuminate\Database\Query\Builder::products.skus()
    • 你有最新版本的 Laravel 吗? whereHas 中对嵌套关系的支持最近才启用。运行composer udpate
    • 好吧,我还在使用 4.1 希望升级不会破坏一切。
    【解决方案2】:

    对于 Laravel 5,试试这个

    $category = Category::with(['products','products.skus'])->whereHas('products.skus', function($query) {
        $query->where('price', '>', 10);
    })->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 2017-02-07
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多