Codeigniter 4 – Query Buider with Model

Query Builder with Model

- Use the db property of the Model to access the Query Builder.

Example:

namespace App\Models;

use CodeIgniter\Model;

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

    public function getUsers()
    {
        return $this->db->table($this->table)->get();
    }
}

Selecting Data

- Use the select() method to specify the columns to retrieve.

Example:

public function getUsers()
{
    return $this->db->table($this->table)->select('name, email')->get();
}

Filtering Data

- Use the where() method to filter data based on conditions.

Example:

public function getUsers()
{
    return $this->db->table($this->table)->where('name', 'John Doe')->get();
}

Joining Tables

- Use the join() method to join multiple tables.

Example:

public function getUsers()
{
    return $this->db->table($this->table)
        ->join('posts', 'posts.user_id = (link unavailable)')
        ->get();
}

Grouping Data

- Use the groupBy() method to group data based on columns.

Example:

public function getUsers()
{
    return $this->db->table($this->table)
        ->groupBy('name')
        ->get();
}

Sorting Data

- Use the orderBy() method to sort data based on columns.

Example:

public function getUsers()
{
    return $this->db->table($this->table)
        ->orderBy('name', 'ASC')
        ->get();
}

I hope this helps! Let me know if you have any further questions or need more information.

Note: Using the Query Builder with a Model in CodeIgniter 4 provides a simple and intuitive way to build and execute database queries. It helps to keep the code organized and maintainable.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0