0

im new in laravel world n didn't know well how to write proper code. i have a query

SELECT c.cityname, count(distinct s.namep) as statecount FROM cities c INNER JOIN patiens s on c.id = s.cityidp GROUP BY c.cityname ORDER BY statecount DESC;

output query like this

enter image description here

in my sql database, its work really well with output like i want, but the problem i can't implemented that query in laravel.

in that query i want get how many every city already used by patiens. thanks a lot for help before

2 Answers 2

2

Because of the count, you will probably need to use an element of Raw expression Laravel QueryBuilder

$result = DB::table('cities c')
             ->join('patiens s','c.id','=','s.cityidp')
             ->select(DB::raw('c.cityname, count(distinct s.namep) as statecount'))
             ->groupBy('c.cityname')
             ->orderBy('statecount','desc')
             ->get();
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the response, that work well with small edited like this in my. "$result = DB::table('cities') ->join('patiens', 'cities.id', '=', 'patiens.cityidp') ->select(DB::raw('cities.cityname, count(distinct patiens.namep) as statecount')) ->groupBy('cities.cityname') ->orderBy('statecount', 'desc') ->get();"
To alias table name you may AS keyword.DB::table('cities AS c')->get(); => select * from cities as c
0

Ideal would be, if you had tables as Models (City, Patien) and Relationships between this two Models.

//City model
public function patiens(){
    return $this->hasMany(Patien::class, 'cityidp');
}

Than you could just do:

$cities = City::withCount('patiens')->get();

And in result loop:

foreach($cities as $city){
    echo $city->cityname." -> ".$city->patiens_count."<br/>";
}

1 Comment

@AntG already answer my question, thanks a lot and you too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.