The WPModel
class is a custom database model class designed for WordPress using the $wpdb
object for database interactions. It provides a fluent interface for building and executing SQL queries.
protected $table;
- The table name with prefix.protected $primaryKey = 'id';
- The primary key of the table.protected $wpdb;
- WordPress database object.protected $selectClause = '*';
- Default select clause.protected $whereClauses = [];
- Array to store WHERE clauses.protected $joinClauses = [];
- Array to store JOIN clauses.protected $orderByClause = '';
- ORDER BY clause.protected $groupByClause = '';
- GROUP BY clause.protected $havingClause = '';
- HAVING clause.protected $limitClause = '';
- LIMIT clause.protected $offsetClause = '';
- OFFSET clause.protected $with = [];
- Relations to eager load.
Initializes the $wpdb
object and sets the table name.
Sets the columns to be selected in the query.
$model->select(['name', 'email']);
Eager loads relationships.
$model->with('posts');
Adds a WHERE clause to the query.
$model->where('status', '=', 'active');
Adds an OR WHERE clause to the query.
Adds WHERE clauses for any of the specified columns.
Adds WHERE clauses for all of the specified columns.
Adds an INNER JOIN clause to the query.
Adds a LEFT JOIN clause to the query.
Adds a RIGHT JOIN clause to the query.
Sets the ORDER BY clause.
Sets the GROUP BY clause.
Sets the HAVING clause.
Sets the LIMIT clause.
Sets the OFFSET clause.
Retrieves a single record by ID.
Retrieves all records based on the current query.
Inserts a new record into the database.
Updates a record with the given ID.
Deletes a record with the given ID.
Returns the count of records based on the current query.
Retrieves the first record based on the current query.
Checks if any records exist based on the current query.
Returns the average value of a column.
Returns the sum of a column.
Returns the maximum value of a column.
Returns the minimum value of a column.
Returns an array of values for a single column.
Selects distinct values in the query.
Updates an existing record or inserts a new one.
Defines a one-to-one relationship.
Defines a one-to-many relationship.
Defines a many-to-many relationship.
Starts a database transaction.
Commits the current transaction.
Rolls back the current transaction.
class Post extends WPModel
{
protected $table = 'posts';
protected $primaryKey = 'ID';
}
$post = new Post();
$post->first();
class Post extends WPModel
{
protected $table = 'posts';
protected $primaryKey = 'ID';
public function postMeta()
{
return $this->hasOne(PostMeta::class, 'post_id', $this->primaryKey);
}
}
class PostMeta extends WPModel
{
protected $table = 'postmeta';
protected $primaryKey = 'post_id';
}
$post = new Post();
$post->with('postMeta')->first();