John Davidson

php - cakephp 4.x query to get results from database

0 comments
Message:


I came across a problem recently that I have to make a find(all) query in cakephp.


Problem is I was unable to call model function to cakephp controller & add a command in function that would allow me to make a find(all) function in cakephp and retrieve all rows in a database that I was looking for.


I would like to make a simple query to make a call to database table that is in database that retrieves rows in table that are matching query.


public function display(){

$query = $HouseParty->find('all', [
'conditions' => ['HouseParty.popular >' => 0],
'contain' => ['title', 'image', 'popular'],
'limit' => 6
]);
$results = $query->all();
var_dump($results);

}

Also what is code to make call to model in Cakephp Controller. So controller knows that we are making calls to models from controller. So we can interact with models from controller because I intend to make multiple calls to different models from same controller in future. Please be helpful looking for a response been stuck on this problem for days just making a question here that is relevant & resourceful for others as well. I would like to make a question come handy to other community members I would just need to get code apart from what I have mentioned above that what code should I write in order to make a call for calling models in one controller - call to multiple models from one controller. Is the above code correct and is so what makes it from giving an error as below. So what is code to make calls to models from database.


Error i get is below:



Call to a member function find() on null




My Answer:
Here is an example of how you can make a find(all) query in CakePHP 4.x:

php
// In your controller
use App\Model\Table\YourModelTable;

public function index()
{
$yourModelTable = new YourModelTable();
$results = $yourModelTable->find()->all();

// Do something with the results
}


Make sure to replace `YourModelTable` with the actual name of your model table. This code snippet demonstrates how to call a model function in a CakePHP controller to perform a find(all) query and retrieve results from the database.

Rate this post

3 of 5 based on 5681 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us