Select query with multiple where conditions in cakephp 3.x
First include these classes into your controller to use objects of these classes
use Cake\ORM\Query;
use Cake\ORM\Table;
use App\Model\Entity\Role;
use Cake\ORM\TableRegistry;
Simple Select query in cakephp 3.x
$tableRegObj = TableRegistry::get('OurTableName'); //database Table name = our_table_name$getAllResults = $tableRegObj->find('all');
$getAllResults will return results object . if you want to count records then you can use count function of this
example =>
echo $getAllResults->count();
If you want fetch data as an array then you can use toArray();
example =>
$getAllResults = $tableRegObj->find('all')->toArray();
If you want to fetch only first row of result data then you can use first()
example=>
$getFirstRow = $getAllResults->first();
2.Fetch Data with conditions
In cakephp 3.x you can use multiple conditions with fetch data from database .example=> Query with conditions
$tableRegObj = TableRegistry::get('OurTableName');
$getAllResults = $tableRegObj
->find()
->select(['field1','field2','field3','total'=>'SUM(field)'])
->where(['category' => 'buy','status'=>'pending'])
->group(['getAllResults.price'])
->order(['price' => 'DESC'])->toArray();
3. Fetch Data by column name in cakephp 3.x
You can also get results by passing your field with query for example if you want to fetch results fron db where username="abc" and email="abc@gmail.com" then your query will be :-$tableRegObj = TableRegistry::get('Users');
$getuserdetails = $tableRegObj->findAllByUsernameAndEmail("abc", "abc@gmail.com"); //return object
$getCurquerySingle = $getuserdetails->first(); //this will select first record of object
first() function will return first row from object that is return by query.
so these are the all queries to get data from database in cakephp 3.x with conditions .
4. Cakephp select only single column from table query
$yourresult = $tableRegObj->find()->select(['quantity'])->where(['category' => 'sell'])->order(['price' => 'ASC']);
Related Posts-
Comments
Post a Comment