-
Notifications
You must be signed in to change notification settings - Fork 39
Db Row
Строка в таблице, некий недо-ActiveRecord
Для корректной работы требует соответствующий класс Table
<?php
namespace Application\Users;
/**
* @property integer $id
* @property string $login
* @property string $created
* @property string $updated
*/
class Row extends \Bluz\Db\Row
{
}
$userRow = new \Application\Users\Row();
$userRow -> login = 'username';
$userRow -> save();
Аннотация в блоке комментариев необходимы лишь для поддержки автодополнения в IDE
Можно вытащить связанный записи в одном SQL запросе следующим образом:
<?php
// sql query with relation one to one
$sql = "
select
users.*
, g.name AS __Groups_name
from users
left join groups g on users.group_id = g.id
";
// use it from controller
$userRows = $db->fetchObjects($sql, array(), '\Application\Users\Row');
// use it from Users\Table
$userRows = self::fetch($sql);
// result
foreach($userRows as $userRow)
$groupRow = $userRow->getRelation('Groups');
Обратите внимание на SELECT, в нём можно увидеть конструкцию - g.name AS __Groups_name, тут Groups - имя связанной Row и его атрибут.
В Row существуют следующие хуки:
- afterRead - после получения данных из БД
- beforeSave - до сохранения записи посредством
insertилиupdate - afterSave - после
- beforeInsert - до сохранения записи посредством
insertи послеbeforeSave - afterInsert - после
- beforeUpdate - до сохранения записи посредством
updateи послеbeforeSave - afterUpdate - после
- beforeDelete - до удаления записи
- afterDelete - после
Пример использования хуков:
<?php
namespace Application\Users;
/**
* @property integer $id
* @property string $login
* @property string $created
* @property string $updated
*/
class Row extends \Bluz\Db\Row
{
public function beforeInsert()
{
$this->created = gmdate('Y-m-d H:i:s');
}
public function beforeUpdate()
{
$this->updated = gmdate('Y-m-d H:i:s');
}
}
Предложение по реализации связей на уровне таблиц. Есть следующая структура БД:
| users | | posts | | posts_tags | | tags |
| id | | id | | postId | | id |
| name | | title | | tagId | | name |
| userId |
Структура хранения связей:
<?php
// high level links
array(
'users' => ['posts'],
'posts' => ['users', 'posts_tags', 'tags'],
);
// low level links
array(
'users:posts' => ['id' => 'userId'],
'posts:users' => ['userId' => 'id'],
'posts:posts_tags' => ['id' => 'postId'],
'tags:posts_tags' => ['id' => 'tagId'],
'posts:tags' => ['posts:posts_tags', 'tags:posts_tags'],
)
Пример вытягивание связи posts:tags:
<?php
$tags = $post->getRelation('tags');
// inside
$relation = 'posts:tags';
if (array_key_exists($relation, Table::$relations)) { };
if (sizeof(Table::$relations[$relation]) > 1) {
// many to many
foreach (Table::$relations[$relation] as $relationLink) {
// ... build query
}
} elseif (sizeof(Table::$relations[$relation]) == 1) {
// many to one
// ... build query
}
Инициализация связей в конкретных сущностях таблиц:
<?php
namespace Application\Users;
/**
* @property $id
* @property $name
*/
class Row extends \Bluz\Db\Row {
}
class Table extends \Bluz\Db\Table {
protected $table = 'users'; // can retrieve from NS
protected $primary = ['id']; // can retrieve from DB info
}
namespace Application\Posts;
/**
* @property $id
* @property $title
* @property $userId
*/
class Row extends \Bluz\Db\Row {
/* can be "magic" */
public function getUser() {
return $this->getRelation('users');
}
/* can be "magic" */
public function getTags() {
return $this->getRelation('tags');
}
}
class Table extends \Bluz\Db\Table {
/* manyToOne */
public function init()
{
// to another table
// field, table => foreighKey
$this->toOne('userId', ['users' => 'id']);
// many to many over third table
// field, table => foreighKey, table => foreignKey, table => foreighKey
$this->toMany('id', ['posts_tags' => 'postId'], ['posts_tags' => 'tagId'], ['tags' => 'id']);
}
}
namespace Application\Tags;
/**
* @property $id
* @property $name
*/
class Row extends \Bluz\Db\Row {
}
class Table extends \Bluz\Db\Table {
/* manyToOne */
public function init()
{
$this->toMany('id', ['posts_tags' => 'tagId'], ['posts_tags' => 'postId'], ['posts' => 'id']);
}
}
Acl
Application
Auth
Cache
Common
— Exception
— Collection
— Container
— Helper
— Options
— Singleton
Config
Controller
— Data
— Mapper
—— Crud
—— Rest
— Reflection
Crud
— Crud Table
Db
— Row
— Table
— Relations
— Query
Debug
EventManager
Grid
Http
Layout
Logger
Mailer
Messages
Nil
Proxy
Registry
Request
Response
Router
Session
Translator
Validator
View