I'm writing a quick throwaway method to import users from an old table to my new cake app. I've imported the old users table (old_users) into my cake app db. Basically I need to just do a select all form the old_users table, then loop through them and add them to the new users table using somehting like $newuser->create('old_username', 'old_password');
However, I didnt want to create a model etc for the temp table as this import will only be run once. So my question is - how can I do a basic select to get all the users from this table from a cake method within the users controller. I was thinking somehting like this:
public function admin_importOldUsers() {
$db = $this->getDataSource();
$db->fetchAll('SELECT * FROM old_users');
}
But it failswith the error:
Call to undefined method UsersController::getDataSource()
I cant find much in the docs on how to query another db table (without a model) from within a controller....
Could anyone point me in the right direction?
Thanks in advance
To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method.
To apply ordering, you can use the order method: $query = $articles->find() ->order(['title' => 'ASC', 'id' => 'ASC']); When calling order() multiple times on a query, multiple clauses will be appended. However, when using finders you may sometimes need to overwrite the ORDER BY .
$post = $this->Posts->get($id, [ 'contain' => ['Postmeta'] ]); echo "<pre>"; print_r(debug($post));die; It will show all result along with sql query syntax. Here we are using debug for show result along with sql query.
To manually run a standard SQL query in CakePHP without a model, you can use the query
method on any model that is available to the controller (it doesn't matter which model you use):
class MyController extends AppController
{
public function index()
{
$result = $this->AnyModel->query("SELECT * FROM my_table");
}
}
CakePHP 1.3 - Models
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With