Welcome Guest, Not a member yet? Register   Sign In
Models in CI4
#1

Hi

I really need someone to give me a quick overview/ comparison of models in 3 <-> 4. I had absolutely no problem with the way models worked in 3, loved it in fact, but trying to work with the way models function now in CI4 seems to be an absolute nightmare. I know it's different and I just haven't got used to it yet, but is anyone able to give me some very basic examples of how to set a bunch of functions in a model file then call them when needed?

so far I've managed to load a function with

PHP Code:
$db = \Config\Database::connect('default'false);
$this->usersModel = new UsersModel($db);

echo 
$this->usersModel->check_login_credentials(1,1); 


but this errors (I think due to query building bit), and is an awful lot more work/ typing than the CI3 way of loading models and instantly being able to access all their functions. Am I doing something wrong?

As for the query itself, this is the closest I can get to a simple query in CI4, but it still gives me errors. 

PHP Code:
public function __construct(ConnectionInterface &$db)
            {
                    $this->db =& $db;
            }

public function 
check_login_credentials($username$password)
{
$query $this->db->table('users.*')->where('user_index',1)->get()->row();
return 
$query;




I am utterly confused at the CI4 way of using models if anyone can help. I am simply trying to echo out a row from the database so I know that it works before building upon that, but can't even get that working smoothly.
Reply
#2

I think the Database section of the user guide got you confused. 

Take a look a the tutorial. There's a very simple example of what you're trying to do: https://codeigniter4.github.io/userguide...ction.html
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

You can do it exactly as you've done it in the past. Add a new method to the model and call it. The new models basically take a lot of the functionality that many of the publicly available MY_Model classes had and build them into the core.

The reason that query is giving you errors is because you're treating the table() call like a select call, which it isn't. The table method just specifies which table to use. This is necessary in 4 to keep queries from "bleeding" into other queries as would often happen in CI3 if you weren't very careful.

PHP Code:
$this->db->table('users')... 

However, you also have some helper functions in your model you can use now for that same query.

PHP Code:
public function checkLoginCredentials($username$password) {
    
$user $this->where('username'$username)->first();

    if (
$user === null) {
       return 
false;
    }

    ... 
check password stuff here...

Reply




Theme © iAndrew 2016 - Forum software by © MyBB