dongpu3898 2018-08-19 05:46 采纳率: 100%
浏览 771
已采纳

如何在Laravel中合并三个集合?

我有3个集合:

+----------------+  +----------------+  +----------------+ 
|     Posts      |  |   PostImages   |  |   PostFiles    |
+----------------+  +----------------+  +----------------+
|   id           |  |   id           |  |   id           |
|   title        |  |   post_id      |  |   post_id      |
|   description  |  |   patch        |  |   patch        |
|   user_id      |  +----------------+  |   description  |
+----------------+                      +----------------+

Controllers:

$posts = User::find($userdata->id)->posts;

$postids = Post::where('user_id', $userdata->id)->pluck('id')->toArray();

$images = PostImage::wherein('post_id ', $postids )->get()->All();

$files = Docs::wherein('post_id', $postids )->get()->All();

是否可以在不使用循环的情况下组合这三个集合,以获得以下结构:

[post1] => [
    title => title,
    content => content,
    images => collection [
                        image1 => patch,
                        image2 => patch,
                        image3 => patch,
                        ],
    Files => [
        [0] => [
            file1 => patch,
            description1 => description
        ],
        [1] => [
            file2 => patch,
            description2 => description
        ]
    ]
],
[post2] => [
    title => title,
    content => content,
    images => collection [
                        image1 => patch,
                        image2 => patch,
                        image3 => patch,
                        ],
    Files => [
        [0] => [
            file1 => patch,
            description1 => description
        ],
        [1] => [
            file2 => patch,
            description2 => description
        ]
    ]
],

有办法吗?

  • 写回答

1条回答 默认 最新

  • douti8321 2018-08-19 05:53
    关注

    Yes, Laravel's 'WITH' is just what you need.

    Example:

    In you post model add these functions.

    public function images()
    {
      return $this->hasMany(YouImageModel::class, 'post_id');
    }
    
    public function files()
    {
     return $this->hasMany(YourFileModel::class, 'post_id');
    }
    

    So when getting post you can eager load the images.

    $posts = Post::where('user_id', $userdata->id)->with(['images', 'files])->posts;
    

    Here is the doc link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答