PHP code example of lin-orm / lite

1. Go to this page and download the library: Download lin-orm/lite 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/ */

    

lin-orm / lite example snippets


#[Table(name: 'users', comment: '用户表')]
class User
{
    #[PrimaryKey, AutoIncrement, Type(type: 'int', length: 11)]
    public $id;
}

/**
 * @Table(name: 'users', comment: '用户表')
 */
class User
{
    /**
     * @PrimaryKey
     * @AutoIncrement
     * @Type(type: 'int', length: 11)
     */
    public $id;
}

namespace app\model;

use Lin\Lite\attr\Table;
use Lin\Lite\attr\PrimaryKey;
use Lin\Lite\attr\AutoIncrement;
use Lin\Lite\attr\Type;
use Lin\Lite\attr\DefaultValue;
use Lin\Lite\attr\Comment;
use Lin\Lite\attr\CreatedAt;
use Lin\Lite\attr\UpdatedAt;
use Lin\Lite\attr\BelongsTo;
use Lin\Lite\attr\HasMany;

#[Table(comment: '配置')]
class Config
{
    #[PrimaryKey, AutoIncrement, Type('int', 11), Comment('ID')]
    public $id;

    #[Type('varchar', 100), DefaultValue(''), Comment('名称')]
    public $name;

    #[Type('int', 11), Comment('配置类型ID'), BelongsTo(ConfigType::class)]
    public $config_type_id;

    #[Type('text'), Json, Comment('JSON 值')]
    public $vals;

    #[CreatedAt, Type('datetime'), Comment('创建时间')]
    public $created_at;

    #[UpdatedAt, Type('datetime'), Comment('更新时间')]
    public $updated_at;

    #[HasMany(ConfigValue::class)]
    public $values;
}

namespace app\model;

use Lin\Lite\attr\Table;
use Lin\Lite\attr\PrimaryKey;
use Lin\Lite\attr\AutoIncrement;
use Lin\Lite\attr\Type;
use Lin\Lite\attr\DefaultValue;
use Lin\Lite\attr\Comment;
use Lin\Lite\attr\CreatedAt;
use Lin\Lite\attr\UpdatedAt;
use Lin\Lite\attr\BelongsTo;
use Lin\Lite\attr\HasMany;

/**
 * @Table(comment: '配置')
 */
class Config
{
    /**
     * @PrimaryKey
     * @AutoIncrement
     * @Type(type: 'int', length: 11)
     * @Comment(comment: 'ID')
     */
    public $id;

    /**
     * @Type(type: 'varchar', length: 100)
     * @DefaultValue(value: '')
     * @Comment(comment: '名称')
     */
    public $name;

    /**
     * @Type(type: 'int', length: 11)
     * @Comment(comment: '配置类型ID')
     * @BelongsTo(model: 'app\model\ConfigType')
     */
    public $config_type_id;

    /**
     * @Type(type: 'text')
     * @Json
     * @Comment(comment: 'JSON 值')
     */
    public $vals;

    /**
     * @CreatedAt
     * @Type(type: 'datetime')
     * @Comment(comment: '创建时间')
     */
    public $created_at;

    /**
     * @UpdatedAt
     * @Type(type: 'datetime')
     * @Comment(comment: '更新时间')
     */
    public $updated_at;

    /**
     * @HasMany(model: 'app\model\ConfigValue')
     */
    public $values;
}

use Lin\Lite\DB;

// 基于表名
$db = DB::table('config');

// 基于模型(推荐)
$model = new Config();
$db = DB::model($model);

// 简单条件,参数绑定
->where('id = ?', 1)
->where('status = ?', 1)
->where('id > ?', 10)

// WHERE 多个自动 AND
->where('status = ?', 1)->where('sort > ?', 0)

// IN 条件自动展开
->where('id IN (?)', [1, 2, 3])

// 非空才添加条件
->whereNotEmpty('name = ?', $name)

// LIKE 模糊搜索,非空才添加,自动加 %
->like('name', $keyword)
->like('name LIKE ?', $keyword) // 手动写 LIKE 也支持

->order('id desc')
->order('sort asc') // 多个 ORDER BY 逗号拼接

->limit(10)
->limit(10, 20)

->offset(10)

// 分页,自动计算 offset
->page(1, 10)   // 第1页,每页10条,最大不超过100
->page(1, 10, 50) // 自定义最大条数

->select('id', 'name')
->select('id', 'name', 'sort')

->join('INNER JOIN config_type ON config.type_id = config_type.id')
->join('LEFT JOIN other ON ...')

->group('type_id')
->having('count(*) > 1')

// 查询多条,结果赋值传入变量
$list = [];
DB::model(new Config())->find($list);

// 查询一条,结果赋值传入变量
$item = null;
DB::model(new Config())->where('id = ?', 1)->first($item);

// 查询单个字段值,结果赋值传入变量
$name = null;
DB::model(new Config())->where('id = ?', 1)->value('name', $name);

// 查询多个字段值,返回二维数组,结果赋值传入变量
$list = [];
DB::model(new Config())->values(['id', 'name'], $list);

// 查询计数,结果赋值传入变量
$total = 0;
DB::model(new Config())->count($total);

// 检查是否存在,结果赋值传入变量
$exists = false;
DB::model(new Config())->where('name = ?', 'test')->exists($exists);

// 模型对象,有主键值 → 更新,无主键值 → 插入
$model = new Config();
$model->name = 'test';
DB::model($model)->save($model);
// 返回 DB 实例,影响行数需要自行判断

// 自动回写自增ID:插入后 $model->id 已赋值

// 单条插入
$model = new Config();
$model->name = 'test';
DB::model($model)->create($model);

// 条件更新多条字段
DB::model(new Config())
    ->where('status = ?', 0)
    ->updates(['sort' => 100]);

// 更新单个字段
DB::model(new Config())
    ->where('id = ?', 1)
    ->update('sort', 100);

// 检查 name 唯一,如果已存在抛出异常
// 检查唯一性不会关联链式调用条件,仅使用传入的条件+主键条件(主键值不为空时,主键是链式,一般从模型实例化开始获得)
DB::model(new Config())
    ->checkUnique('名称已存在', 'name = ?', $name);

// 更新时自动排除当前数据,即加上排除当前主键条件
$config = new Config();
$config->id = 1;
$config->name = 'new name';
DB::model($config)->checkUnique('名称已存在', 'name = ?', $name);

// 条件删除
// 尽量使用条件删除,避免删除所有数据
DB::model(new Config())->where('status = ?', 0)->delete();

// 模型中注解
class Config
{
    #[BelongsTo(ConfigType::class)]
    public $config_type_id;
}

class ConfigType
{
    #[HasMany(Config::class)]
    public $configs;
}

// 查询时 preload() 预加载
$list = [];
DB::model(new Config())
    ->preload(ConfigType::class) // 属性名,自动从注解读关系
    ->find($list);

// 访问结果
foreach ($list as $item) {
    echo $item->configType->name;
}

// HasMany 预加载
$list = [];
DB::model(new ConfigType())
    ->preload(Config::class)
    ->find($list);

foreach ($list as $type) {
    foreach ($type->configs as $config) {
        echo $config->name;
    }
}

// 自定义预加载条件
$list = [];
DB::model(new Config())
    ->preload(ConfigType::class, function ($db) {
        $db->order('name desc');
    })
    ->find($list);

// 同步表结构,只增加不修改不删除
DB::model(new ConfigType())->syncTable();
DB::model(new Config())->syncTable();

use Lin\Lite\DB;

// 查询(返回二维数组)
$rows = DB::query('SELECT * FROM config WHERE id = ?', [1]);

// 执行(INSERT/UPDATE/DELETE)
DB::exec('UPDATE config SET sort = 0 WHERE id = ?', [1]);

// 获取最后插入ID
$id = DB::lastInsertId();

// 开启调试
DB::model(new Config())->debug()->find($list);

use Lin\Lite\PgsqlConn;

PgsqlConn::connect('default', '127.0.0.1', 'postgres', '123456', 'mydb', 5432);

PgsqlConn::connect('pg1', '10.0.0.1', 'postgres', '123456', 'db1');
PgsqlConn::connect('pg2', '10.0.0.2', 'postgres', '123456', 'db2');

use Lin\Lite\Conn;
use Lin\Lite\PgsqlConn;
use Lin\Lite\DB;

// 初始化两个库
Conn::init('127.0.0.1', 'root', '123456', 'mysql_db');
PgsqlConn::connect('pg', '127.0.0.1', 'postgres', '123456', 'pg_db');

// 操作 MySQL 表
DB::table('users')->where('id = ?', 1)->value('name', $name);

// 操作 PostgreSQL 表,用法完全一致,? 自动转为 $1
DB::table('logs', 'pg')->where('type = ?', 'info')->limit(10)->find($list);
DB::model($order, 'pg')->save();

use Lin\Lite\DB\Conn;
 
$host = 'localhost';
$user = 'root';
$password = '123456';
$database = 'lite';
$port = 3306;
Conn::init($host, $user, $password, $database, $port);

use Lin\Lite\Conn;
use Lin\Lite\DB;

// 连接默认数据库
Conn::init('127.0.0.1', 'root', '123456', 'db1');
// 连接第二个数据库
Conn::connect('db2', '192.168.1.100', 'root', '123456', 'db2');
// 连接第三个
Conn::connect('db3', '10.0.0.1', 'root', '123456', 'db3');

// 默认连接(不传第二个参数,老代码无需改动)
DB::table('users')->where('id = ?', 1)->value('name', $name);

// 操作 db2
DB::table('users', 'db2')->where('id = ?', 1)->value('name', $name);
DB::model($order, 'db2')->save();

// 传入连接实例也可以
DB::table('logs', Conn::getInstance('db3'))->create(['msg' => 'done']);

// 多库之间随意切换
DB::table('users', 'db1')->where('id = ?', 1)->value('name', $name);
DB::table('orders', 'db2')->where('status = ?', 'paid')->limit(10)->values(['id'], $data);
DB::table('logs', 'db1')->create(['msg' => 'back to db1']);

interface ConnInterface
{
    public function getSymbol(): string;           // 名称标识符包裹符,如 `、"
    public function query(string $sql, array $args = []);  // 查询,有返回结果
    public function exec(string $sql, array $args = []);   // 执行,无返回结果
    public function lastInsertId(): int|string;    // 最后插入ID
    public function begin();                       // 开始事务
    public function commit();                      // 提交事务
    public function rollback();                    // 回滚事务
}

use Lin\Lite\DB;

// 实现 ConnInterface 后替换连接
DB::setConn(new MyCustomConn());

use Lin\Lite\DB;
// 方式1,通过函数调用事务,结束自动提交,抛异常自动回滚
DB::transaction(function() {
    DB::model(new Config())->create(...);
    DB::model(new Log())->create(...);
});

// 方式2,自由控制事务,手动提交或回滚
try {
    DB::begin();
    DB::model(new Config())->create(...);
    DB::model(new Log())->create(...);
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
}

// 闭包方式
DB::model(new Config())
    ->scope(function($db) {
        $db->where('status = ?', 1);
    })
    ->find($list);

// 函数方式
function active(DB $db): void
{
    $db->where('status = ?', 1);
}

DB::model(new Config())
    ->scope('active')
    ->find($list);

// 链式中调用 debug() ,执行终结方法会输出 SQL语句 和参数
// 终结方法:find, first, count, exists, values, value, syncTable, delete, save, create, update, tableExists, getExistingColumns, getExistingForeignKeys, getPkName, getFieldsAttr
// 其实就是在真正执行sql的地方会打印sql语句和参数
DB::model(new Config())
    ->debug()
    ->where('id = ?', 1)
    ->first($item);

// 设置调试打印等级,1: 打印sql语句+参数,2: 1+耗时+返回行数,3: 2+对象执行时间
// 默认:2
DB::model(new Config())
    ->debug()
    ->debugLevel(2)
    ->where('id = ?', 1)
    ->first($item);

class Config
{
    public function beforeFind() {} // 查询前
    public function afterFind() {} // 查询后
    public function beforeSave() {} // 保存前, save方法,也会执行插入和更新钩子,反之不会,即插入和更新不会执行save钩子方法,保存后相同
    public function afterSave() {} // 保存后
    public function beforeCreate() {} // 插入前
    public function afterCreate() {} // 插入后
    public function beforeUpdate() {} // 更新前
    public function afterUpdate() {} // 更新后
    public function beforeDelete() {} // 删除前
    public function afterDelete() {} // 删除后
}