How to use conditional for this query in Laravel 5.2

落花浮王杯 提交于 2019-12-24 09:58:02

问题


Here is the scenario

Table: Users

id   | name  | grade  | subject
---- | ------|--------|------
1    | Mark  |   a    |   science
2    | Earl  |   a    |   english
3    | John  |   c    |   english
4    | Mike  |   d    |   science
5    | Matt  |   e    |   english

What I want to do is populate the grades that are non-repeating or non-duplicate grades but for english subject only

So it should just show

c
e

I've got this far

controller:

$grades = user::select('grade', DB::raw('COUNT(grade) as gradecount'))
->where('subject', 'english')
->groupBy('grade')
->having('gradecount', '=',1)
->get();

blade:

@foreach ($grades as $grade)
            {{ $grade }}
            @endforeach

However, this query gives this

a
c
e

回答1:


You'll want to do something like this:

SELECT grade
FROM Users
WHERE id IN (
    SELECT id 
    FROM Users
    GROUP BY grade
    HAVING COUNT( grade ) = 1
) AND subject = 'english'`

Query builder has a ->whereIn that you should be able to use. Too lazy to test, but something like this may work.

$ids = user::select('id')
->groupBy('grade')
->having('gradecount', '=',1)
->get();

$grades = user::select('grade')
->whereIn('id', $ids)
->where('subject', 'english')
->get();


来源:https://stackoverflow.com/questions/43905484/how-to-use-conditional-for-this-query-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!