如何在foreach中显示其他数据?

时间:2018-10-01 13:36:49

标签: php laravel foreach relation

在您可以观看每个小组的表演功能中,我将所有具有相同标签的文章加载。投票最多的文章将单独显示在顶部。另外,我指出了该组中项目的平均评分。这是我的函数的样子:

public function show($id)
    {
        $group = group::find($id);

            $tagIdArray = $group->tags->pluck('id')->all();

            $mostvotedarticle = Article::where('type', 4)->whereIn('privacy', [1, 3])
                ->whereHas('tags', function($query) use ($tagIdArray) {
                    $query->whereIn('tags.id', $tagIdArray);
                }, '>=', count($tagIdArray))
                ->orderByVotes()->first();

            $articledown = Article::where('status', 1)->whereHas('tags', function($query) use ($tagIdArray) {
                $query->whereIn('tags.id', $tagIdArray);
            }, '>=', count($tagIdArray))->downVotesAll()->count();

            $articleup = Article::where('status', 1)->whereHas('tags', function($query) use ($tagIdArray) {
                $query->whereIn('tags.id', $tagIdArray);
            }, '>=', count($tagIdArray))->upVotesAll()->count();

            $ratio = null;

            if($articleup + $articledown == 0) {
                $ratio = 0;
            } else {
                $ratio = ($articleup*100)/($articleup + $articledown);
            }

    return view('singlegroup',compact('groups','mostvotedarticle', 'ratio'));
}

在概述页面上,各个组以foreach循环显示:

功能:

public function index()
    {
        $user = Auth::user();
        $groups = $user->groups()->latest()->with('tags')->paginate(20);

        return view('groups', compact('groups'));
    }

视图:

@foreach ($groups as $group)
        {{$group->name}}                      
        <img src="-----load mostvotedarticle that is in this group------" alt="" />
        <div class="progress-bar-primary" style="width:{{$ratio}}%;">
@endforeach 

如何在foreach循环中显示最投票的文章和组的评分?

商品模型

public function scopeOrderByVotes($query)
    {
        $query->leftJoin('Article_activities', 'Article_activities.article_id', '=', 'articles.id')
            ->selectRaw('articles.*, count(Article_activities.id) as aggregate')
            ->groupBy('articles.id')
            ->orderBy('aggregate', 'desc');
    }

    public function scopeDownVotesAll($query)
    {
        $query->leftJoin('Article_activities', 'Article_activities.article_id', '=', 'articles.id')
            ->selectRaw('articles.*, count(Article_activities.id) as aggregate')
            ->where('Article_activities.activity', '=', '0');
    }

    public function scopeUpVotesAll($query)
    {
        $query->leftJoin('Article_activities', 'Article_activities.article_id', '=', 'articles.id')
            ->selectRaw('articles.*, count(Article_activities.id) as aggregate')
            ->where('Article_activities.activity', '=', '1');
    }

1 个答案:

答案 0 :(得分:1)

您需要将所有内容都放入And the game begins! QS 组中

select t.*
from t
where t.id = (select t2.franchise_id
              from t t2
              order by id
              limit 4, 1
             );