【问题标题】:Laravel Eloquent in many to many relation limit relational data [duplicate]Laravel Eloquent在多对多关系限制关系数据[重复]
【发布时间】:2022-01-19 06:08:32
【问题描述】:

我有很多关系。 Product、Category 和 category_product 作为支点。我想通过 Category 获取产品,但我需要每个 Category 10 产品。

这是我的查询

 Category::with(['grocery_product')->get();

类别模型:

   public function grocery_product(): BelongsToMany
   {
       return $this->belongsToMany(Product::class)->limit(10);
   }

但是这里的限制不起作用。如果我删除 limit(10),那么我会得到与该类别相关的所有产品。

注意:我也尝试过 take(10) 函数。

如何获取每个类别的10个产品?

【问题讨论】:

    标签: php laravel laravel-8


    【解决方案1】:

    默认情况下,laravel 没有任何开箱即用的方案解决方案。

    所以你可以使用eloquent-eager-limit by staudenmeir

    你可以这样做。

    //Category Model
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
      public function grocery_product(): BelongsToMany
    {
        return $this->belongsToMany(Product::class);
    }
    

    Product 模型内部使用相同的特征

    //Product Model
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
    

    在控制器中。

    //to get latest 5 `grocery_product` on each category
    $fiveGroceryOfEachProduct = Category::with(['grocery_product' => function ($query) {
        $query->latest()->limit(5);
    }])->get();
    

    在不使用此包的情况下调用限制方法将对整体查询应用limti。不是在每个模型上。

    可以查看github issuehere

    编辑查询兼容性问题

    所以作为包装suggests。请设置

    'strict' => false, 
    

    在您的 config/database.php 文件中,为 MariaDB/MySql 连接设置 'strict' => false。并确保重新启动您的开发服务器

    【讨论】:

    • 完美。非常感谢:)
    • 如果解决方案对您有帮助,请接受我的回答
    猜你喜欢
    • 2019-06-13
    • 2015-05-19
    • 2019-03-26
    • 1970-01-01
    • 2013-02-09
    • 2023-02-05
    • 2013-05-27
    • 2013-05-15
    • 2016-11-03
    相关资源
    最近更新 更多