PHP code example of alex-lee / php-model

1. Go to this page and download the library: Download alex-lee/php-model library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alex-lee / php-model example snippets


\model\PDOBJ::setConfig('127.0.0.1', 'database', 'username', 'password');

use model\Model;

class Item extends Model
{
    // 可选:显式指定表名与主键;不指定则按类名推导(去掉 Model 后缀并转小写)
    public $table = 'item';
    public $pk    = 'id';

    // 一对一:Item.id = Item2.id
    public function item2()
    {
        return $this->hasOne(Item2::class, 'id', 'id');
    }

    // 一对多:Page.type 指向 Item.id,定义时还可继续追加查询条件
    public function page()
    {
        return $this->hasMany(Page::class, 'type', 'id')
                    ->where('page_id', '<=', 100);
    }
}

// where 三参数
$res = Item::where('id', '=', 1)->select();

// where 数组
$res = Item::where([
    ['id', '>', 3],
    ['status', '=', 1],
])->select();

// 闭包嵌套分组 + OR
$res = Item::where(function ($query) {
    $query->where('id', 'in', [1, 2, 3])
          ->whereOr('status', '=', 2);
})->select();

// 字段 / 排序 / 分页
$res = Item::field(['id', 'item_name'])
           ->order('id DESC')
           ->limit(1, 20)   // 第 1 页,每页 20 条
           ->select();

// 单条与聚合
$one  = Item::where('id', '=', 1)->find();
$count = Item::where('status', '=', 1)->count();

// 原生 SQL(只读查询)
$rows = Item::sql('select * from item limit 10');

// 新增,返回自增主键
$id = Item::insert(['item_name' => 'test']);

// 更新,返回影响行数
$affected = Item::where('id', '=', 2)->update(['item_name' => 'new']);

// 保存:按 $where 查询,存在则更新,不存在则插入
Item::save(['item_name' => 'new'], ['id' => 2]);

// 按主键删除
Item::delete(3);

// with 预加载:查询时一并取出关联数据
$res = Item::where('id', '=', 2)->with(['page', 'item2'])->select();
sdump($res->toArray());   // 关联数据已合入 page / item2 键

// load 延迟加载:查询后按需加载,支持闭包限定关联查询条件
$res = Item::where('id', '=', 1)->select();
$res->load([
    'page' => function ($query) {
        $query->where('page_id', '=', 3);
    },
    'item2',
]);

// 闭包式:异常自动回滚并抛出
Item::transaction(function () {
    Item::where('id', '=', 2)->update(['item_name' => '666']);
});

// 手动式
Item::beginTransaction();
try {
    Item::where('id', '=', 2)->update(['item_name' => '666']);
    Item::commit();
} catch (\Exception $e) {
    Item::rollback();
}
bash
composer 

src/
├── Model.php            模型基类:属性读写、表名推导、关联定义入口
├── Query.php            查询构造器:SQL 拼装、CURD、聚合查询、事务、SQL 日志
├── Collection.php       数据集:链式数组操作、关联加载
├── PDOOBJ.php           PDO 连接单例
└── relation/            关联(Relation 基类、HasOne、HasMany)
bash
composer install

# PowerShell
$env:DB_PASSWORD = '数据库密码'
php test.php

# CMD / Linux
set DB_PASSWORD=数据库密码   # Linux: export DB_PASSWORD=数据库密码
php test.php