emneslab/wp-eloquent

WordPress Eloquent ORM 集成

1.0.0 2024-09-05 03:17 UTC

This package is auto-updated.

Last update: 2024-09-15 17:58:12 UTC


README

此库允许您在WordPress中无缝使用Laravel的Eloquent ORM,扩展WordPress原生数据库处理的能力。

包安装

要安装此包,请更新您的composer.json文件如下

{
    "require": {
        "emneslab/wp-eloquent": "dev-main"
    }
}

然后运行以下命令

$ composer install

使用示例

基本用法

$db = \Emneslab\ORM\Database\Connection::instance();

var_dump($db->table('users')->find(1));
var_dump($db->select('SELECT * FROM wp_users WHERE id = ?', [1]));
var_dump($db->table('users')->where('user_login', 'john')->first());

// OR with DB facade
use Emneslab\ORM\Support\Facades\DB;

var_dump(DB::table('users')->find(1));
var_dump(DB::select('SELECT * FROM wp_users WHERE id = ?', [1]));
var_dump(DB::table('users')->where('user_login', 'john')->first());

使用WordPress模型

您可以使用WordPress模型,就像Eloquent模型一样

use Emneslab\ORM\WP\Post;

// Fetch all posts
var_dump(Post::all());

// Filter by post type and status
var_dump(Post::type('page')->get()->toArray()); // Fetch all pages
var_dump(Post::status('publish')->get()->toArray()); // Fetch all published posts
var_dump(Post::type('page')->status('publish')->get()->toArray()); // Fetch all published pages

使用自定义表

您可以定义自定义WordPress表的模型,利用Eloquent的功能

<?php
namespace CustomNamespace;

use Emneslab\ORM\Database\Eloquent\Model;

class CustomTableModel extends Model {
    protected $table = 'custom_table_name';
    protected $fillable = ['column1', 'column2', 'column3'];
    public $timestamps = false;
    protected $primaryKey = 'ID';
    protected $guarded = ['ID'];

    public function getTable()
    {
        if (isset($this->table)) {
            return $this->getConnection()->getTablePrefix() . $this->table;
        }

        return parent::getTable();
    }
}

模式管理

您可以使用Laravel的模式构建器来创建或修改表

use Illuminate\Database\Schema\Blueprint;
use Emneslab\ORM\Support\Facades\Schema;

// Dropping a table
Schema::drop('wp_test_database_table');

// Creating a new table
Schema::create('test_database_table', function (Blueprint $table) {
    $table->id();
});

工作原理

  • Eloquent用作查询构建器。
  • 查询使用WordPress原生的WPDB类执行。
  • 此设置确保与WordPress调试工具(如debug-barquery-monitor)兼容。
  • 它不会创建任何额外的MySQL连接,使其轻量级且高效。

最低要求

  • PHP >= 7.2
  • WordPress >= 6.2

作者

Emneslab

此包受Tareq Hasan的wp-eloquent的启发,并为希望利用Eloquent ORM的WordPress开发者提供了额外的支持和功能。