Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Model->where method does not exist #4583

Closed
patch-lee opened this issue Apr 18, 2021 · 6 comments
Closed

Model->where method does not exist #4583

patch-lee opened this issue Apr 18, 2021 · 6 comments

Comments

@patch-lee
Copy link

Hi, CI4 Team

I just ran into a problem when calling Model->where method

When ever I called $this->where, $this->asArray()->where, or (new UserModel)->where , I would encouter an error: 500 method does not exist.

    "title": "TypeError",
    "type": "TypeError",
    "code": 500,
    "message": "method_exists(): Argument #1 ($object_or_class) must be of type object|string, null given",
    "file": "/Users/caliv3r/Documents/Works/online-training/web_api/vendor/codeigniter4/framework/system/BaseModel.php",
    "line": 1770,
    "trace": [...]

Here is my model

<?php

namespace App\Models;

use CodeIgniter\Model;
use Exception;

class UserModel extends Model
{
	public function __construct()
	{
		helper('database');
	}

	protected $table                = 'users';
	protected $primaryKey           = 'user_id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = true;
	protected $protectFields        = true;
	protected $allowedFields        = [
		'emp_code', 'first_name', 'last_name',
		'password', 'is_admin', 'dept_id',
		'created_by', 'updated_by', 'deleted_by'
	];

	// Dates
	protected $useTimestamps        = true;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	public function findUserByEmpCode(string $empCode)
	{
		$user = $this
			->asArray()
			->where(['emp_code' => $empCode])
			->first();

		if (!$user)
			throw new Exception('User does not exist for specified employee code');

		return $user;
	}

	public function findUserByEmpCodeAndPassword(string $empCode, string $password)
	{
		$user = $this
			->asArray()
			->where(['emp_code' => $empCode, 'password' => $password])
			->first();

		if (!$user) throw new Exception('Invalid Credentials');

		return $user;
	}
 }

I have read through CI documentation which says
This query may be modified by interjecting Query Builder commands as needed prior to calling this method:

$users = $userModel->where('active', 1)
                   ->findAll();

But I can't use this method as the docs said.

What am I missing here? please kindly advice.

Thanks :)

@paulbalandan
Copy link
Member

Can you show us the full stack trace of the exception thrown?

@paulbalandan
Copy link
Member

And, have you tried changing the constructor to this?

public function __construct($db, $validation)
{
    parent::__construct($db, $validation);
    helper('database');
}

@patch-lee
Copy link
Author

patch-lee commented Apr 18, 2021

Can you show us the full stack trace of the exception thrown?

{
    "title": "TypeError",
    "type": "TypeError",
    "code": 500,
    "message": "method_exists(): Argument #1 ($object_or_class) must be of type object|string, null given",
    "file": "/Users/caliv3r/Documents/Works/online-training/web_api/vendor/codeigniter4/framework/system/BaseModel.php",
    "line": 1770,
    "trace": [
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/vendor/codeigniter4/framework/system/BaseModel.php",
            "line": 1770,
            "function": "method_exists",
            "args": [
                null,
                "where"
            ]
        },
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/vendor/codeigniter4/framework/system/Model.php",
            "line": 832,
            "function": "__call",
            "class": "CodeIgniter\\BaseModel",
            "type": "->",
            "args": [
                "where",
                [
                    {
                        "emp_code": "admin",
                        "password": "P@ssw0rd"
                    }
                ]
            ]
        },
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/app/Models/UserModel.php",
            "line": 109,
            "function": "__call",
            "class": "CodeIgniter\\Model",
            "type": "->",
            "args": [
                "where",
                [
                    {
                        "emp_code": "admin",
                        "password": "P@ssw0rd"
                    }
                ]
            ]
        },
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/app/Controllers/Auth.php",
            "line": 27,
            "function": "findUserByEmpCodeAndPassword",
            "class": "App\\Models\\UserModel",
            "type": "->",
            "args": [
                "admin",
                "P@ssw0rd"
            ]
        },
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/vendor/codeigniter4/framework/system/CodeIgniter.php",
            "line": 936,
            "function": "login",
            "class": "App\\Controllers\\Auth",
            "type": "->",
            "args": []
        },
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/vendor/codeigniter4/framework/system/CodeIgniter.php",
            "line": 432,
            "function": "runController",
            "class": "CodeIgniter\\CodeIgniter",
            "type": "->",
            "args": [
                {}
            ]
        },
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/vendor/codeigniter4/framework/system/CodeIgniter.php",
            "line": 333,
            "function": "handleRequest",
            "class": "CodeIgniter\\CodeIgniter",
            "type": "->",
            "args": [
                null,
                {
                    "handler": "file",
                    "backupHandler": "dummy",
                    "storePath": "/Users/caliv3r/Documents/Works/online-training/web_api/writable/cache/",
                    "cacheQueryString": false,
                    "prefix": "",
                    "file": {
                        "storePath": "/Users/caliv3r/Documents/Works/online-training/web_api/writable/cache/",
                        "mode": 416
                    },
                    "memcached": {
                        "host": "127.0.0.1",
                        "port": 11211,
                        "weight": 1,
                        "raw": false
                    },
                    "redis": {
                        "host": "127.0.0.1",
                        "password": null,
                        "port": 6379,
                        "timeout": 0,
                        "database": 0
                    },
                    "validHandlers": {
                        "dummy": "CodeIgniter\\Cache\\Handlers\\DummyHandler",
                        "file": "CodeIgniter\\Cache\\Handlers\\FileHandler",
                        "memcached": "CodeIgniter\\Cache\\Handlers\\MemcachedHandler",
                        "predis": "CodeIgniter\\Cache\\Handlers\\PredisHandler",
                        "redis": "CodeIgniter\\Cache\\Handlers\\RedisHandler",
                        "wincache": "CodeIgniter\\Cache\\Handlers\\WincacheHandler"
                    }
                },
                false
            ]
        },
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/public/index.php",
            "line": 44,
            "function": "run",
            "class": "CodeIgniter\\CodeIgniter",
            "type": "->",
            "args": []
        },
        {
            "file": "/Users/caliv3r/Documents/Works/online-training/web_api/vendor/codeigniter4/framework/system/Commands/Server/rewrite.php",
            "line": 45,
            "args": [
                "/Users/caliv3r/Documents/Works/online-training/web_api/public/index.php"
            ],
            "function": "require_once"
        }
    ]
}

@patch-lee
Copy link
Author

And, have you tried changing the constructor to this?

public function __construct($db, $validation)
{
    parent::__construct($db, $validation);
    helper('database');
}

No, I haven't tried yet.
But If that so, what arguments should I supply for new UserModel() ?

I'm calling UserModel in my controller.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;
use CodeIgniter\HTTP\ResponseInterface;
use Exception;

class Auth extends BaseController
{
	public function login()
	{
		$rules = [
			'username' => 'required',
			'password' => 'required|min_length[0]|max_length[20]'
		];

		$input = $this->getRequestInput($this->request);
		if (!$this->validateRequest($input, $rules)) {
			return $this->getResponse($this->validator->getErrors(), ResponseInterface::HTTP_BAD_REQUEST);
		}

		$userModel = new UserModel();
		try {
			// $user = $userModel->where(['emp_code', $input['username'], $input['password']])->first();
			$user = $userModel->findUserByEmpCodeAndPassword($input['username'], $input['password']);
		} catch (Exception $e) {
			return $this->getResponse(['401NF' => $e->getMessage()], ResponseInterface::HTTP_UNAUTHORIZED);
		}
                // ... rest of code
        }
}

Thanks for reply :)

@paulbalandan
Copy link
Member

Yes, I forgot that. Change the parameters to nullable.

public function __construct($db = null, $validation = null)
{
    parent::__construct($db, $validation);
    helper('database');
}

@patch-lee
Copy link
Author

Yes, I forgot that. Change the parameters to nullable.

public function __construct($db = null, $validation = null)
{
    parent::__construct($db, $validation);
    helper('database');
}

Thank you so much! worked like a charm!

Closing this issue now, thanks again for the help :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants