duanci19881003
2015-04-14 22:26
浏览 341
已采纳

Laravel:需要解决foreach循环问题

What i'm trying to do is basically have the "latest" episodes show for a series that is has a status of "ongoing" below is the code i have so far.

The problem i a facing is that I can't seem to make the foreach loop for episodes work for the series. Wit hthe current code what it does is shows the same variables. Rather what i think is happening is that it loops the same query for each series so that the same variable pops up for each series.

Can anyone help me out here?

Also the way the episodes are linked is by using the title_id for the titles so in the table for episodes, they are liked by 'title_id', I wouldn't know what to do with that in this sequence though.

        <?php $titles = DB::table('titles')->whereNotNull('poster')->where('status', '=', 'ongoing')->orderBy('updated_at', 'desc')->limit(12)->get(); ?>
        @foreach ($titles as $title)

            <?php $episodes = DB::table('episodes')->orderBy('created_at', 'desc')->limit(1)->get(); ?>

            @foreach ($episodes as $episode)
            <figure class="col-lg-2 col-md-3 col-sm-4  pretty-figure">
                <div class="home-episode-number">
                    {{ $episode->episode_number }}
                </div>
                <div class="flip-containerw">
                    <div class="flipper">
                      <a href="{{ Helpers::episodeUrl($title->title, $episode->title_id, 'series', $episode->season_number, $episode->episode_number) }}"><img src="{{ $episode->poster ? $episode->poster : '/assets/images/noimageepisode.png' }}" alt="" class="img-responsive"></a>
                    </div>
                </div>
                <div class="home-anime-name">
                    <a href="{{ Helpers::episodeUrl($title->title, $episode->title_id, 'series', $episode->season_number, $episode->episode_number) }}" class="series-name-link"> {{ str_limit($title->title, 23, '...') }} </a>
                </div>
            </figure>
    @endforeach                 
@endforeach
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanjuan3931 2015-04-15 01:10
    已采纳

    You are not following some basic design patterns, like, for instance, the Model-View-Controller structure.

    MVC

    It's not good practice to have DB calls inside your view, wich you are doing. You should do it inside your model, or in a repository. And pass it trought the controller.

    You would avoid a lot of headache if you start using eloquent properly.

    Eloquent

    Now, answering your question:

    If you want to get the episode for the title in the loop, try using a where:

    $episodes = DB::table('episodes')->where('title_id,'=',$title->id)->orderBy('created_at', 'desc')->limit(1)->get();
    

    That query will retrieve just one episode (limit(1)).

    点赞 打赏 评论

相关推荐 更多相似问题