2

I wanna select specific columns from table. Not all columns.

$this->userModel->where($where)->first();

I'm using this but it returns all data.

Aksen P
  • 4,564
  • 3
  • 14
  • 27
Hamid Ejaz
  • 88
  • 1
  • 1
  • 7

2 Answers2

1

According to the CI4 query builder documentation you can use select() in this way:

$db      = \Config\Database::connect();
$builder = $db->table('mytablename');        // 'mytablename' is the name of your table

$builder->select('userid, username');       // names of your columns, single string, separated by a comma
$builder->where('userid', 5);                // where clause
$query = $builder->get();

return $query;

where() could be possible to use in 4 ways, you can choose.

This stuff should be placed in Model file, method of which would return $query set of DB data.

Aksen P
  • 4,564
  • 3
  • 14
  • 27
  • This solve my problem thanks a lot for getting records i add this thing in code $query->getFirstRow($this->tempReturnType) – Hamid Ejaz Jan 26 '20 at 21:52
  • @user1951608, you're welcome! Now you have CI4 documentation) It's weird that CI3 and CI4 have different websites, I thought they'd updated CI3 website, but no, they've created separated website. – Aksen P Jan 26 '20 at 21:56
  • 1
    CI4 has improved a lot from CI3, and the CI3 userbase is higher as well, so separate website is better in my point of view. – Vishal Kumar Sahu Sep 20 '20 at 22:50
  • $builder->select('userid','username'); did not work for me. It selected only userid. In CI 4 docs, $builder->select() takes only the first parameter as a string of your column names. So it should be a string with comma separated values: $builder->select('userid, username'); – ChelaTheGreat Aug 13 '22 at 03:12
1

(Tested under CI 4.2.7)

There is also a select method in the model, which accepts an array of columns:

$userModel->select(['id','name'])->where('id', 1)->first();
acala
  • 332
  • 3
  • 11