erwang/korm

此包已被废弃,不再维护。未建议替代包。

PHP ORM

v2.0.0 2017-07-28 09:42 UTC

README

PHP ORM ⛔️ 已弃用

设置

首先必须调用连接类设置。

$connection = \KORM\Connection::setup('name','pdo_dsn', 'username', 'password');

连接到一个mysql数据库

$connection = \KORM\Connection::setup('connectionName','mysql:host=localhost;dbname=database', 'username', 'password');

带有选项

$connection = \KORM\Connection::setup('connectionName','mysql:host=localhost;dbname=database', 'username', 'password', array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));

创建一个类

数据库中的每个表都需要一个与表名相同的类

class Table extends \KORM\Object{
}

类名转换为小写 例如,存储书籍

class Book extends \KORM\Object{
}

Book 对象将被存储在 book 表中

定义连接

Book::setConnection($connection);

根据id获取一行

$book = new Book($id);

将在 $book 中加载具有id=1的 book 表中的所有数据

创建一行

$book = new Book();

存储一个对象

$book = new Book($id);
$book->title='Les Misérables';
$book->store();

删除一个对象

$book = new Book($id);
$book->delete();

查找对象

查找一个对象

$book = Book::findOne(['title'=>'Les Misérables']);

这将返回一个 Book(第一个找到的)

查找多个对象

$authors = Author::find(['nationality'=>'French']);

这将返回一个包含所有法国作者的数组

如果您需要复杂的where子句,可以使用where

$books = Book::where('pages>:nbpages',['nbpages'=>100]);

这将返回一个包含超过100页的书籍的数组

如果您想进行更复杂的查询

$books = Book::query('select book.* from book,author where author.id=:author_id and pages>:nbpages and author.id=book.author_id',['nbpages'=>100,'author_id'=>1]);

这将返回一个包含id为1的作者的超过100页的书籍的数组

$books = Book::getAll();

这将返回表中的所有书籍

关系

一对多

//create a book
$lesMiserables = new Book();
$lesMiserables->title='Les Misérables';
$lesMiserables->store();

//create an author
$hugo=new Author();
$hugo->name='Victor Hugo';
$hugo->store();

//create a relation
$lesMiserables->author=$hugo;
$lesMiserables->store();

//get the book
$book = new Book($lesMiserables->id);
$author = $book->author; //return the object Author from table author

多对多

//create tags
$tag1=new Tag();
$tag1->text='french';
$tag1->store();

$tag2=new Tag();
$tag2->text='Roman';
$tag2->store();
$lesMiserables->tag=[$tag1,$tag2];
$lesMiserables->store();

//find book from many
$booksWithFrenchTag = $tag1->book;

计数

//get the number of books
Book::count();

//get the number of books from an author
Book::count(['author_id'=>$author->id]);

填充一个对象

//get data from an array
$post=['firstname'=>'Marcel','lastname'=>'Proust'];
//create a new author
$author=new Author();
$author->populate($post);
$author->store();

截断表

//with foreign key check
Author::truncate();
//without foreign key check
Author::truncate(false);

删除表

//with foreign key check
Author::drop();
//without foreign key check
Author::drop(false);