The Exist method can retrieve whether data with the given Where conditions exists more efficiently instead of querying the complete data result and returning it.

Method definition:

  1. func (m *Model) Exist(where ...interface{}) (bool, error)

Example SQL

This is the MySQL table structure used in the following example code.

  1. CREATE TABLE `user` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `name` varchar(45) NOT NULL
  4. PRIMARY KEY (`id`)
  5. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Usage Example

Querying complete data:

  1. // SELECT * FROM `user` WHERE (id > 1) AND `deleted_at`=0
  2. g.Model("user").Where("id > ?", 1).All()

Using the Exist method:

  1. // SELECT 1 FROM `user` WHERE (id > 1) AND `deleted_at`=0 LIMIT 1
  2. g.Model("user").Where("id > ?", 1).Exist()

As you can see, it uses SELECT 1 at the underlying level to query the result, meaning if the result exists, it returns 1; otherwise, it returns nothing.