GithubHelp home page GithubHelp logo

dimitribouteille / wp-orm Goto Github PK

View Code? Open in Web Editor NEW
47.0 2.0 5.0 319 KB

WordPress ORM with Eloquent, an object-relational mapper that makes it enjoyable to interact with your database.

Home Page: https://packagist.org/packages/dbout/wp-orm

License: MIT License

PHP 94.64% Shell 5.36%
wordpress-orm eloquent-orm phinx migration-tool wordpress orm database eloquent mysql wordpress-development

wp-orm's Introduction

WordPress ORM with Eloquent

GitHub Release tests Packagist Downloads Eloquent version

Important

The phinx package will be removed in a future release in order to use the Laravel migration system. It is therefore advisable to stop using the tool. More info.

WordPress ORM with Eloquent is a small library that adds a basic ORM into WordPress, which is easily extendable and includes models for core WordPress models such as posts, post metas, users, comments and more. The ORM is based on Eloquent ORM and uses the WordPress connection (wpdb class).

πŸ’‘ To simplify the integration of this library, we recommend using WordPress with one of the following tools: Bedrock, Themosis or Wordplate.

Features

  • βœ… Support core WordPress models: Comment, Option, Post, TermTaxonomy, Term, User, PostMeta and UserMeta
  • βœ… Support core WordPress post type: Article, Attachment and Page
  • βœ… Based on core WordPress database connection (wpdb class), no configuration required !
  • βœ… Custom functions to filter models with meta
  • ❀️ Easy integration of a custom post type
  • ❀️ Easy model creation for projects with custom tables
  • ❀️ All the features available in Eloquent, are usable with this library !

Not yet developed but planned in a future version:

  • πŸ—“οΈ Create custom comment type
  • πŸ—“οΈ Meta casting (e.g. Attribute Casting)

Documentation

This documentation only covers the specific points of this library, if you want to know more about Eloquent, the easiest is to look at the documentation of Eloquent :)

Installation

Requirements

The server requirements are basically the same as for WordPress with the addition of a few ones :

Installation

You can use Composer. Follow the installation instructions if you do not already have composer installed.

composer require dbout/wp-orm

In your PHP script, make sure you include the autoloader:

require __DIR__ . '/vendor/autoload.php';

πŸŽ‰ You have nothing more to do, you can use the library now! Not even need to configure database accesses because it's the wpdb connection that is used.

Contributing

We encourage you to contribute to this repository, so everyone can benefit from new features, bug fixes, and any other improvements. Have a look at our contributing guidelines to find out how to raise a pull request.

wp-orm's People

Contributors

dimitribouteille avatar rafaucau avatar renovate[bot] avatar szepeviktor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

wp-orm's Issues

Add a code example on how to create corresponding tables for models in database

Normally we use the following code to create tables in WordPress:

 add_action('init', [$this, 'migrate']);


function migrate() {
        global $wpdb;

        $PluginSettings = $this->ConfigService->getPluginSettings();
        $charsetCollate = $wpdb->get_charset_collate();

        $sqlConversationTable = <<<EOD
            CREATE TABLE %s (
                  id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                  accountId BIGINT(20) UNSIGNED NOT NULL,
                  userId BIGINT(20) UNSIGNED NULL,
                  chatbotId BIGINT(20) UNSIGNED NOT NULL,
                  ipAddress VARCHAR(32) NULL,
                  created DATETIME NOT NULL,
                  updated DATETIME NOT NULL,
                  PRIMARY KEY (id)
                ) %s;
        EOD;

        $sqlConversationTable = sprintf(
            $sqlConversationTable, $this->ConfigService->getChatbotConversationTable(), $charsetCollate
        );

        $sqlConversationMessageTable = <<<EOD
            CREATE TABLE %s (
                  id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                  conversationId BIGINT(20) UNSIGNED NOT NULL,
                  author VARCHAR(32) NULL,
                  message longtext NULL,
                  created DATETIME NOT NULL,
                  updated DATETIME NOT NULL,
                  PRIMARY KEY (id)
                ) %s;
        EOD;

        $sqlConversationMessageTable = sprintf(
            $sqlConversationMessageTable, $this->ConfigService->getChatbotConversationMessageTable(), $charsetCollate
        );

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta([
            $sqlConversationTable,
            $sqlConversationMessageTable
        ]);

}

But how it should be done using your package? I guess we still need to use 'dbDelta' piece, but code for table creation should be done in a different way. Perhaps we have to use QueryBuilder or somehow get table schema from Models?

If we don't need to use WordPress approach but use migrations instead. Then anyway how to run these migrations only once, so it doesn't try to create tables on each page init

Add models scopes/helpers

FindOneBy

  • User::findOneByEmail
  • User::findOneByLogin
  • Option::findOneByName
  • Post::findOneByName
  • Post::findOneByGuid

Taps

[BUG]: deleteOrFail() open transaction internally and at the moment transaction is opened but it is never closed.

#17 (comment)


@dimitriBouteille one more thing, deleteOrFail() open transaction internally and at the moment transaction is opened but it is never closed.

public function deleteOrFail()
{
    if (! $this->exists) {
        return false;
    }

    return $this->getConnection()->transaction(function () {
        return $this->delete();
    });
}

In the query log, I see only: "[06-Mar-2024 12:55:51 UTC] START TRANSACTION;" and that's it.

It looks like WordPress can be launched with different type of tables: InnoDB, MyISAM, etc.

InnoDB tables are transactional tables.
Non-transactional tables would be e.g MyISAM.

Please check that code is working good with transactional table and non-transactional ones.
If it's running with non-transactional table, it shouldn't try to create the transaction.

I think need to add a couple of unit tests.

3.x - Migrate to PHP 8.x

Enum support

  • Option::AUTOLOAD => \Dbout\WpOrm\Providers\PostStatus
  • Post::STATUS => \Dbout\WpOrm\Providers\YesNo
  • Post::PING_STATUS => \Dbout\WpOrm\Providers\PingStatus

Errors

  • Class Dbout\WpOrm\Models\Post inherits both Illuminate\Database\Eloquent\Model::CREATED_AT and Dbout\WpOrm\Api\PostInterface::CREATED_AT
  • Class Dbout\WpOrm\Models\Post inherits both Illuminate\Database\Eloquent\Model::UPDATED_AT and Dbout\WpOrm\Api\PostInterface::UPDATED_AT

[BUG] Hard dependencies

In the require-dev in composer.json, should'nt

                "phpunit/phpunit": "9.6.17",
                "rector/rector": "1.0.2",
                "roots/wordpress": "6.4.3",

be

                "phpunit/phpunit": "^9.6",
                "rector/rector": "^1.0",
                "roots/wordpress": "^6.4",

?

[BUG]: "This database engine does not support upserts" but MySQL supports it

Describe the bug

When I try to use the upsert method, I get this error:

Fatal error: Uncaught RuntimeException: This database engine does not support upserts. in /var/www/vhosts/localhost/vendor/illuminate/database/Query/Grammars/Grammar.php:1206 Stack trace: #0 /var/www/vhosts/localhost/vendor/illuminate/database/Query/Builder.php(3646): Illuminate\Database\Query\Grammars\Grammar->compileUpsert() #1 /var/www/vhosts/localhost/vendor/illuminate/database/Eloquent/Builder.php(1086): Illuminate\Database\Query\Builder->upsert() #2 /var/www/vhosts/localhost/vendor/illuminate/support/Traits/ForwardsCalls.php(23): Illuminate\Database\Eloquent\Builder->upsert() #3 /var/www/vhosts/localhost/vendor/illuminate/database/Eloquent/Model.php(2334): Illuminate\Database\Eloquent\Model->forwardCallTo() #4 /var/www/vhosts/localhost/vendor/dbout/wp-orm/src/Orm/AbstractModel.php(85): Illuminate\Database\Eloquent\Model->__call() #5 /var/www/vhosts/localhost/vendor/illuminate/database/Eloquent/Model.php(2346): Dbout\WpOrm\Orm\AbstractModel->__call() #6 /var/www/vhosts/localhost/packages/plugins/****/includes/Admin.php(31): Illuminate\Database\Eloquent\Model::__callStatic() #7 /var/www/vhosts/localhost/html/wp/wp-includes/class-wp-hook.php(324): ****\Admin->***\{closure}() #8 /var/www/vhosts/localhost/html/wp/wp-includes/class-wp-hook.php(348): WP_Hook->apply_filters() #9 /var/www/vhosts/localhost/html/wp/wp-includes/plugin.php(517): WP_Hook->do_action() #10 /var/www/vhosts/localhost/html/wp/wp-admin/admin.php(259): do_action() #11 /var/www/vhosts/localhost/html/wp/wp-admin/edit.php(10): require_once('...') #12 {main} thrown in /var/www/vhosts/localhost/vendor/illuminate/database/Query/Grammars/Grammar.php on line 1206

Steps to reproduce the issue

  1. Create Model
  2. Try to use upsert method on it, for example:
TestStat::upsert(
	[[
		'test_id' => $test_id,
		'count' => 1,
	]],
	[ 'test_id' ],
	[ 'count' => Database::getInstance()->raw( 'count + 1' ) ]
);

Expected behavior

The upsert method should work, as MySQL / MariaDB supports it.

Your setup

  • WordPress Version: 6.5.3
  • Module version: 3.1.3
  • Are you using framework ?: Bedrock
  • Database: MariaDB 10.5

Additional context

This is implemented in MySqlGrammar:
https://github.com/illuminate/database/blob/c57f5c8d3e55d9c952a2ad5f432bcb1dc2d3322c/Query/Grammars/MySqlGrammar.php#L246-L269

But not in Grammar:
https://github.com/illuminate/database/blob/5a121a1507ea69dfd416a618415dada9dd4a50b4/Query/Grammars/Grammar.php#L1306

2.x - Add flat table support

Wordpress offers an EAV system, which involves loading via several SQL requests each metas which is not necessarily efficient especially in production.

The idea is therefore to create a flat table system in which all the metas (or some) would be saved in a table.

In addition to this system, there must also be a mechanism for indexing the data.

[BUG]: saveOrFail doesnt throw QueryException

Database->insert()

should throw QueryException like you do that in

Database->selectOne()

because when we use

Model->saveOrFail()

it calls

Database->insert()

internally and if if any errors occurs during query, it doesn't throw the Exception now.

[BUG]: joinToMeta Unknown column

[Unknown column ''_is_default_season'' in 'on clause']

Actual query :

select `posts`.* 
from `posts` 
inner join `postmeta` as `_is_default_season` on `_is_default_season`.`meta_key` = `_is_default_season` and `_is_default_season`.`post_id` = `posts`.`ID` 
where `_is_default_season`.`meta_value` = 'yes' and `post_type` = 'registration_season' limit 1

Expected query :

select `posts`.* 
from `posts` 
inner join `postmeta` as `_is_default_season` on `_is_default_season`.`meta_key` = '_is_default_season' and `_is_default_season`.`post_id` = `posts`.`ID` 
where `_is_default_season`.`meta_value` = 'yes' and `post_type` = 'registration_season' limit 1

app.ERROR: ErrorException: Call to undefined function wp_orm_get_phinx_config()

i have a error when il try to create migration

my config-phinx.php

<?php

use Roots\WPConfig\Config;

/**
 * And load wordpress
 */
require 'web/wp/wp-load.php';

/**
 * Export phinx config
 */


return wp_orm_get_phinx_config([
    'migrations_path' => 'database/migrations',
    'db_user' => Config::get('DB_USER'),
    'db_password' => Config::get('DB_PASSWORD'),
    'db_name' => Config::get('DB_NAME'),
    'db_host' => Config::get('DB_HOST'),
]);

[FEATURE] Add Illuminate\Support\Facades\DB facade

I'm encountering an issue when trying to use DB::raw. The error message indicates a problem with the facade root not being set.

//...
use Illuminate\Support\Facades\DB;
//...
TestStat::upsert(
	[[
		'test_id' => $test_id,
		'count' => 1,
	]],
	[ 'test_id' ],
	[ 'count' => DB::raw( 'count + 1' ) ]
);

PHP Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/vhosts/localhost/vendor/illuminate/support/Facades/Facade.php:352

How can I properly use DB::raw in WordPress context to enable raw SQL expressions?

Comment not saved with

Comment not saved with v3, attribute names not matching with column ...

setContent => setCommentContent ...

[BUG]: AbstractModel::getId() not working with UID

Describe the bug

A clear and concise description of what the bug is.

Steps to reproduce the issue

A clear and concise description to reproduce the bug.

Expected behavior

A clear and concise description of what you expected to happen.

Your setup

  • Wordpress Version: [e.g. 6.4.2]
  • Module version: [e.g. 3.0.0]
  • Are you using framework ?: [e.g. Bedrock, Wordplate, ... - If yes, Please specify the framework and version]

Additional context

Add any other context about the problem here.

Release note

What's Changed

New major version that contains some changes. Many of the changes have no impact on your code if you don’t have a custom model. Conversely, if you have custom models, please take the time to test your code.

⚠️ Several functions have been deprecated, please replace these functions with the new ones. Deprecated functions will be removed in a future release.

❀️ if you have any problem with this news, you can create a ticket:)

πŸ’‘ Versions V1 and V2 are no longer maintained.


Breaking Changes πŸ› 

  • Welcome PHP 8.1 in #6
  • Refactor meta (Post & User) logic
  • Refactor CustomPost logic
  • Update illuminate/database to ^10.0
  • The properties hasOne/hasMany are read-only (property-read)
  • Delete model \Dbout\WpOrm\Models\CustomComment - Planned in a future release

New Features πŸ’Ž

  • Add findOneBy* functions on some models in #12
  • Create multiple taps
  • Create documentations in #7
  • Add Wordpress Enums (PingStatus, PostStatus and YesNo)

Other Changes πŸ–‡οΈ

  • Add PHPStan tool level 5
  • Add PHPCsFixer
  • Create github actions
  • Create issue templates
  • Define default_migration_table and default_database options in \Dbout\WpOrm\Migration\Config::createPhinxConfig()
  • Deprecated some functions in \Dbout\WpOrm\Models\Comment

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.