db->table( $this->table ); foreach ( $conditions as $field => $value ) { if ( is_array( $value ) ) { $query->where( $field, $value[0] ?? '=', $value[1] ); } else { $query->where( $field, '=', $value ); } } return $query->count(); } /** * Get sum of a field based on conditions * * @param string $field * @param array $conditions * * @return float */ public function sum( string $field, array $conditions = [] ) { $query = $this->db->table( $this->table ); foreach ( $conditions as $field_name => $value ) { if ( is_array( $value ) ) { $query->where( $field_name, $value[0] ?? '=', $value[1] ); } else { $query->where( $field_name, '=', $value ); } } return (float) $query->sum( $field ); } /** * Constructor for BookticsModel * * @param Booktics_Database $db */ public function __construct( Booktics_Database $db ) { $this->db = $db; } /** * Create a new record in the database * * @param array $data * * @return mixed|false */ public function create( array $data ) { $filtered = array_intersect_key( $data, array_flip( $this->fillable ) ); $result = $this->db->table( $this->table )->insert( $filtered ); if ( $result > 0 ) { return $this->find( [ 'id' => $result ] ); } return false; } /** * Update an existing record in the database * * @param int $id * @param array $data * * @return mixed */ public function update( int $id, array $data ) { $filtered = array_intersect_key( $data, array_flip( $this->fillable ) ); return $this->db->table( $this->table )->where( 'id', '=', $id )->update( $filtered ); } /** * Delete a record from the database * * @param int $id * * @return mixed */ public function delete( int $id ) { return $this->db->table( $this->table )->where( 'id', '=', $id )->delete(); } /** * Get multiple records from the database with pagination * * @param array $conditions * @param int $page Current page number * @param int $per_page Items per page * * @return array */ public function get( array $conditions = [], int $page = 1, int $per_page = 10, $order_by = [] ) { $query = $this->db->table( $this->table ); foreach ( $conditions as $field => $value ) { if ( is_array( $value ) ) { $query->where( $field, $value[0] ?? '=', $value[1] ); } else { $query->where( $field, '=', $value ); } } $total = $query->count(); $offset = ( $page - 1 ) * $per_page; $data = $query->limit( $per_page )->offset( $offset ) ->order_by( $order_by )->get(); return [ 'items' => $data, 'current_page' => $page, 'per_page' => $per_page, 'total' => $total, 'total_pages' => ceil( $total / $per_page ) ]; } /** * Find a single record from the database * * @param array $conditions * * @return mixed */ public function find( array $conditions = [] ) { $query = $this->db->table( $this->table ); foreach ( $conditions as $field => $value ) { if ( is_array( $value ) ) { $query->where( $field, $value[0] ?? '=', $value[1] ); } else { $query->where( $field, '=', $value ); } } return $query->first(); } public function get_table_name() { return $this->table; } }