Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get Gorm Query Count Result

I want to get rows count for the selected user. I used gorm library. There is no any full example to identify how get count from the selected table.

row = m.DB.Raw("SELECT count(*) as count FROM user_advertisement_categories uac  WHERE uac.user_id = ?", userId).Row()

Gorm's given example doesn't explain how assign count variable. I want to check is there a record in the table for the given user.

Can anyone give me an example code how should I check the user count and if it isn't a record for the user? I should insert and if there was a user in the table I think,I should delete those records and insert new array.

I get a category array for user.

like image 309
user2552863 Avatar asked Sep 19 '25 15:09

user2552863


1 Answers

You can assign the count to a variable as follow:

count := 0
db.Model(&User{}).Where("uac.user_id = ?", "userId").Count(&count)

Where User struct is the one related to the user_advertisement_categories table.

See at Gorm documentation for more details: http://gorm.io/docs/query.html

like image 127
gregorycallea Avatar answered Sep 21 '25 05:09

gregorycallea