bixev/light-orm

Bixev轻量级对象关系管理器

1.0.20 2017-10-11 09:41 UTC

This package is auto-updated.

Last update: 2024-09-13 13:43:22 UTC


README

本ORM旨在以最简单的方式操作数据库中的对象

安装

建议您使用Composer安装InterventionSDK。

composer require bixev/orm "~1.0"

这将安装此库及其所有依赖项。

因此,您的每个PHP脚本都需要引入composer自动加载文件

<?php

require 'vendor/autoload.php';

用法

多种数据库

使用您自己的数据库初始化。默认情况下,$databaseName为null。您可以在模型类中覆盖它

\Bixev\ORM\API::setDatabaseGetter(function($databaseName){
    $db = new \PDO('');
    return $db;
});

$databaseName在模型中使用,用于与正确数据库通信

仓库

获取仓库以操作对象

$exampleRepository = \Bixev\ORM\API::get('Example');

创建一个对象并将其存储到数据库中

$example = $exampleRepository->createNew();
// same as
// $example = new \Bixev\ORM\Example();
$example->example_2_id = 5;
$example->name = "Tom";
$example->save();
echo $example->getId();

通过id检索现有记录

$id = 3;
$example = $exampleRepository->find($id);
// same as
// $example = new \Bixev\ORM\Example($id);
echo $example->name;

通过sql行检索现有记录

$db = new \PDO('');
$row = $db->query("SELECT id, name, example_2_id FROM user")->fetch();
// row has to contain all declared fields
$user = new \Bixev\ORM\Example($row);

搜索

$examples = $exampleRepository->findBy(['name' => "Tom"]);
$examples = $exampleRepository->findAll();
foreach ($examples as $example) {
    echo $example->name;
}

高级集合实例化(通过sql行)

$db = new \PDO('');
$rows = $db->query("SELECT id, name, example_2_id FROM user")->fetchAll();
// rows have to contain all declared fields
$examples = $exampleRepository->newCollection($rows);

搜索单个

$example = $exampleRepository->findOneBy(['name' => "Tom"]);