CodeIgniter Forums
How to write query on Model and Call Model using Controller in Codeigniter 4? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: How to write query on Model and Call Model using Controller in Codeigniter 4? (/thread-74442.html)



How to write query on Model and Call Model using Controller in Codeigniter 4? - msjagan - 09-24-2019

I am trying to fetch values from users table but throws error. Can anyone give sample snippet for the query (Select, Insert)?

PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Model;


class 
UserModel extends Model
{
    protected 
$table                  'users';
    protected $primaryKey             'id';

    protected $allowedFields         = ['username''password'];

 
    public function 
all()
    {
        $users_result $this->db->query('SELECT * FROM users')->result_array();

        return 
$users_result;
    }


Please point out what I am doing wrong with the above code


RE: How to write query on Model and Call Model using Controller in Codeigniter 4? - includebeer - 09-29-2019

You don't need to write the SQL query. Use findAll like this:
PHP Code:
public function all()
{
    return $this->asArray()->findAll();



See the this example: https://codeigniter4.github.io/userguide/tutorial/news_section.html#setting-up-your-model

Like in CI3, you can return the data as an object or as an array. In CI4 use asArray or asObject:
https://codeigniter4.github.io/userguide/models/model.html#runtime-return-type-changes


RE: How to write query on Model and Call Model using Controller in Codeigniter 4? - mohsin khan - 10-01-2019

public function all()
{
return $this->asArray()->findAll();
}

this code not working in ci4 please suggest me how to select table data in ci4


RE: How to write query on Model and Call Model using Controller in Codeigniter 4? - dave friend - 10-01-2019

(10-01-2019, 01:18 AM)mohsin khan Wrote: public function all()
{
    return $this->asArray()->findAll();
}

this code not working in ci4 please suggest me how to select table data in ci4

It would be best if you show your model code. Then accurate help may be possible.


RE: How to write query on Model and Call Model using Controller in Codeigniter 4? - msjagan - 11-17-2019

Guys I found way to pass/fetch values between controller and model with hints you provided.

Let me share the sample CRUD system once it is done.


Thanks Guys