doufan6886 2015-03-19 16:19
浏览 11
已采纳

在Laravel组织儿童收集

Let's say I have athletes who belong to photos that belong to albums that belong to events.

The fastest method for getting photos of an athlete is $athlete->photos;

If I go this direction:

$events= Event::whereHas('albums.photos.athletes', function ($q)
{
   $q->where('athlete_id', $this->athlete->id);

})

It works, but slower, and I'm not able to do things like $events->albums and only return albums that have photos of this particular athlete.

On my page, I want to display photos by event. How can I use $athlete->photos and then organize them by event?

I could loop through all of the photos found from $athlete->photos and build a new array with the hierarchy of event->album->photo but that seems really janky. Is there a better way to do this using Eloquent?

Edit:

This returns EXACTLY the data I need without the need for further queries, but it takes almost 20 seconds to finish.

// Get all athlete media
$competitions = Competition::whereHas('publishedAlbums.publishedMedia.athletes', function ($q)
{
    $q->where('athlete_id', $this->athlete->id);

})
    ->with(array('publishedAlbums.publishedMedia' => function($query)
    {
        $query->whereHas('athletes', function ($q)
        {
            $q->where('athlete_id', $this->athlete->id);

        });
    }))
    ->with(array('publishedAlbums' => function($query)
    {
        $query->whereHas('publishedMedia.athletes', function ($q)
        {
            $q->where('athlete_id', $this->athlete->id);

        });
    }))
    ->get();

With that, I can do things like $competitions->publishedAlbums and it only shows albums that have media for this athlete. BUT it takes a very long time to execute.

  • 写回答

1条回答 默认 最新

  • dsvyc66464 2015-03-19 17:19
    关注

    It seems like this could be greatly simplified.

    Does this get you what you need and is it any faster?

    $competitions = Competition::with('publishedAlbums.publishedMedia.athletes')
        ->whereHas('publishedAlbums.publishedMedia.athletes', function($q)
        {
            $q->where('athlete_id', $this->athlete->id);
        })->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向