doudong8713 2016-01-06 00:33
浏览 28
已采纳

使用匹配的键将数组推入Laravel集合

I have a collection called User, I also have an array containing two models Post relating to the User model.

The User collection contains a primary key id and each model in my Post collection I have a foreign key user_id.

I am currently executing the following:

foreach ($users as $user) {
    foreach ($posts as $post) {
        if ($post->user_id == $user->id) {
            $user->posts->push($post);
        }
    }
}

This somewhat works, but not entirely because it pulls in all related posts instead of the recent two posts a user has made.


The array looks like the following:

enter image description here

My User schema looks like; with a hasMany relationship to Post:

enter image description here

  • 写回答

3条回答 默认 最新

  • dongxia026531 2016-01-11 17:19
    关注

    You cannot use query constraints / eager loading to do this. Doing so will only work if you are retrieving the posts for one user. However, if you try to retrieve the posts for multiple users, it will fail because eager loading / query constraints will limit the related results as a whole. To understand, you have to look at the queries Eloquent generates. Lets take a look at an example where you only need one user's posts.

    $user = User::with(['posts' => function($query) {
        $query->limit(2);
    }])->find(1);
    

    In this example, we are getting a user with a primary key of 1. We also also retrieving his/her posts but limiting it so we only retrieve 2 posts. This works, and it will generate 2 queries similar to this:

    select * from `users` where `users`.`id` = 1 limit 1
    select * from `posts` where `posts`.`user_id` in (1) limit 2
    

    Okay. Now, why doesn't this work if you try to get more than 1 user (or a collection of users)? For example:

    $user = User::with(['posts' => function($query) {
        $query->limit(2);
    }])->get();
    

    In this case, I changed find(1) to get(), and it will generate 2 queries like this:

    select * from `users`
    select * from `posts` where `posts`.`user_id` in (?, ?, ?, ... ?) limit 2
    

    It's important to take a look at the second query. It's retrieving all the related posts, but at the end, you'll see that it has limit 2. In other words, it's limiting the entire related collection to only 2, which is why query constraints do not work for this.

    Achieving this is actually pretty complex, but a fellow member (Jarek Tkaczyk) came up with a solution using MySQL variables, which you can find here: Laravel - Limit each child item efficiently

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算