【问题标题】:how to use take() with every index of array in laravel如何在 laravel 中对数组的每个索引使用 take()
【发布时间】:2019-01-18 12:21:53
【问题描述】:

您好,我想针对每个品牌选择 3 个模型,我在控制器中使用此代码

 $brand = Brand::with (['models' => function ($q){
            $q->take(3);
    }])->get()->toArray();

但是第一品牌只需要3个型号不是全部Here is the image of my dd command 所以告诉我如何为所有品牌选择 3 种型号。

【问题讨论】:

    标签: sql database laravel eloquent


    【解决方案1】:

    我找到了一个解决方案,使用收集方法图可以得到所有品牌的3个模型

      $feed= Brand::with(['models'])->get()->map(function ($query) {
            $query->setRelation('models', $query->models->take(3));
            return $query;
        });
    

    【讨论】:

    • 这会从数据库中加载所有相关模型,然后丢弃不必要的模型。最好只加载所需的模型(见我的回答)。
    猜你喜欢
    • 2023-03-17
    • 2023-03-05
    • 2022-09-23
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多