seixwebdev
seixwebdev

Reputation: 121

Codeigniter 4 'update' from Controller

I'm so confused...

This function runs OK and doesn't throw up any errors... but it doesn't update the row in my table.

Where have I gone wrong?

Controller:

    public function update()
    {     
        $model = new StoreModel();
      
        $model->where('merchant', 'Klip Shop')->set('availability', 'out of stock')->update();
        
    }

Model:

class StoreModel extends Model
{
    protected $table = 'shop';
}

Upvotes: 1

Views: 8430

Answers (2)

seixwebdev
seixwebdev

Reputation: 121

It was an $allowedFields issue with the model, hence nothing was 'allowed' to be updated.

Upvotes: 1

Vickel
Vickel

Reputation: 7997

Since $model->where('merchant', 'Klip Shop')->get() doesn't return anything, it means that you don't have any data you can update.

You need to insert a row first.

  1. you could use the insert() function, if there is no rows detected with the merchant name

or

  1. there is the save() function in CI 4.x which either inserts or updates on duplicate. but to get it to work, you need to set merchant to unique or use a column with an unique key

please read: Saving Data in CI 4.x

edit: you actually got me confused too:

only now I analized your MCV code:

you should have a controller

public function update()
{     
    $model = new StoreModel();
    $model->update();
}  

    

and a model:

class StoreModel extends Model
{
    $db      = \Config\Database::connect();
    $model= $db->table('shop');

    function update(){
        $model->where('merchant', 'Klip Shop')->set('availability', 'out of stock')->update();
    }
}

Upvotes: 1

Related Questions