Select operated value by multi columns from MySQL using Model in CI4

214 views Asked by At

I want to get column of operated value with multi columns from MySQL in CI4 project.

Here is what I tried.

There are 3 fields qty, size, unit_price in table products and I want to get multiplied value of all of these 3 fields.

class ProductModel extends Model
{
    protected $allowedFields = ['size', 'qty', 'unit_price'];

    public function getPriceOfOneProduct()
    {
        return $this
            ->select('qty * size * unit_price AS price_of_one_product')
            ->findAll();
    }
}

As you can see I'm trying to get a column like this: qty * size * unit_price

But it's not indicated in $allowedFields so CI4 returns error like this:

`Unknown column 'qty * size * unit_price' in 'field list' `

Do I must use query builder or is there any solution for this issue? Please kindly answer my question if you know how to handle this. Thank you.

1

There are 1 answers

1
Abdulla Nilam On

Do like this

class ProductModel extends Model
{
    protected $table = 'products';

    public function getPriceOfOneProduct()
    {
        $query = $this->db->query('SELECT (qty * size * unit_price) AS price_of_one_product FROM products');
        return $query->getResult();
    }
}