Welcome Guest, Not a member yet? Register   Sign In
Append all SELECT queries with an extra WHERE in model
#1

(This post was last modified: 09-10-2023, 11:55 AM by sjender.)

Hi,
Is there a way in CI 4 to have ALL the SELECT (find/findall) queries done by a specific model to append by an extra WHERE condition?
In this case I want 3 models to do an extra: WHERE user_id = 1234.
But instead of doing it query by query, I would like do have the model to do that.
That way it's safer in case I forget 1 query....
I have found callbacks, but I'm not sure they can alter the query as well???
Reply
#2

(09-10-2023, 11:55 AM)sjender Wrote: I have found callbacks, but I'm not sure they can alter the query as well???

Yes, you can use Model Events.
https://codeigniter4.github.io/CodeIgnit...del-events
Reply
#3

Thanks.

I will probably need beforefind then.
I see how I can alter the query data, but not the query itself. Does the manuals have an example for that as well?
Reply
#4

It seems there is no sample code.

You can get the Query Builder for the table,
https://codeigniter4.github.io/CodeIgnit...ry-builder
but inside a model, it should be $this->builder().
And just call where() method you need.
Reply
#5

(This post was last modified: 09-11-2023, 08:23 AM by sjender.)

Yes, got it...

What is, in your opinion,  the best way to get the USER_ID into this method...


PHP Code:
    protected $beforeFind = ['userSpecific'];

    
    
protected function userSpecific()
    {
        $this->builder()->where('user_id'$userId);
    
Reply




Theme © iAndrew 2016 - Forum software by © MyBB