Laravel:检查行是否存在单个查询

时间:2016-10-13 08:10:25

标签: php sql laravel

我对可能有反应的文章发表评论,这些文章是基于IP匿名给出的。

反应表:

id | comment_id | ip | type

应用\注释

class Comment extends Model
{
    public function article() {
        return $this->belongsTo('App\Article');
    }

    public function reactions() {
        return $this->hasMany('App\Reaction')
                ->selectRaw('*, COUNT(type) as count')
                ->groupBy('type')
                ->orderBy('count', 'desc');
    }
}

ArticleController @指数:

public function index()
{
    $articles = Article::orderBy('views', 'desc')->get();

    return view('wiki')->withArticles($articles);
}

如何在上面的单Article::orderBy查询中获取用户当前IP(如果有)给出的反应?即,

Reaction::where(['comment_id' => $id, 'ip' => $_SERVER['REMOTE_ADDR']])->count();

可以在循环内检查每条评论,但这显然效率不高......

它应该是这样的:

@foreach ($articles as $article)
    @foreach ($comments as $comment)
        @if ($comment->given_reaction [or something])
            // ...
        @endif
    @endforeach
@endforeach

1 个答案:

答案 0 :(得分:0)

你有没有试过这样的事情:

$ip = $_SERVER['REMOTE_ADDR'];

$articles = Article::with(['comments' => function($q) use ($ip) {
    $q->with('reactions' => function($q) use ($ip) {
         $q->where('ip' => $ip)
    })
}])->orderBy('views', 'desc')->get();
相关问题