fernandozueet / laravel-doctrine-repository
使用 Laravel Doctrine 的完整仓库模型
Requires
- php: >=7.2.0
- beberlei/doctrineextensions: ^1.1
- laravel-doctrine/orm: 1.4.*
- scienta/doctrine-json-functions: ~4.0
- symfony/property-access: ^4.1
- symfony/serializer: ^4.1
Requires (Dev)
- phpunit/dbunit: >=1.2
- phpunit/phpunit: 5.5.*
- phpunit/phpunit-selenium: >=1.2
README
使用 Laravel Doctrine 的完整仓库模型。
通知
以 doctrine laravel 库作为仓库类的基类。 laravel doctrine 库的文档
要求
- PHP 7.2
- Laravel 5.6 - 文档
包
- doctrine: 2.6 - 文档
- laravel-doctrine/orm: 1.4 - 文档
- beberlei/doctrineextensions: 1.1 - 文档
- symfony/property-access: 4.1 - 文档
- symfony/serializer: 4.1 - 文档
- syslogic/doctrine-json-functions: 2.0 - 文档
文档
- 安装
- 逐步操作
- 示例
- 使用不同的数据库连接
- 实例化创建的仓库
- 插入数据 (INSERT)
- 更新数据 (UPDATE)
- 更新查询数据 (UPDATE)
- 删除数据 (DELETE)
- 选择数据 (SELECT)
- 按 ID 查找
- 事务
- Dql
- WHERE 和 HAVING 选项
- ORDER BY 选项
- GROUP BY 选项
- 额外函数
安装
使用 composer 安装此包
composer require fernandozueet/laravel-doctrine-repository
更新 composer 后,将 ServiceProvider 添加到 config/app.php 中的 providers 数组
Ldr\Core\DoctrineRepositoryServiceProvider::class,
要发布配置,请使用
php artisan vendor:publish --tag="configRepository"
逐步操作
1- 配置数据库连接 .env
2- 配置额外的 doctrine 信息。 config/doctrine.php
3- 生成实体
php artisan make:doctrine-repository:entities
4- 生成仓库文件。
文件将默认创建在 app/Repositories 文件夹中。您可以在 config/doctrine.php 文件中更改文件夹。
注意!使用相同的实体名称
php artisan make:doctrine-repository User
在文件夹中创建文件
php artisan make:doctrine-repository SubPath/User
示例
示例类仓库
文件: app/Repositories/User/UserDocRepository.php
<?php /** * User entity repository. * * Code generated by cli command. * * @see http://github.com/fernandozueet/laravel-doctrine-repository * * @copyright 2018 */ namespace App\Repositories\User; use Ldr\Src\DoctrineBaseRepository; class UserDocRepository extends DoctrineBaseRepository implements UserRepositoryInterface { /** * Construct. */ public function __construct() { parent::__construct(); $this->main($this->fkEntities, $this->mAlias, __CLASS__); } /*------------------------------------------------------------------------------------- * CONFIGS *-------------------------------------------------------------------------------------*/ /** * Foreign key entities names. * * @var array */ private $fkEntities = ['UserGenre']; /** * Main alias. * * @var string */ private $mAlias = 'u'; /*------------------------------------------------------------------------------------- * GENERAL *-------------------------------------------------------------------------------------*/ /** * Method of insertion in the database. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return object */ public function create(array $params): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setCreateArray([ 'fieldTest1', 'fieldTest2:fk=classNameFk', //foreign key ], $params); } /** * Method to update. To update more than one data, use the method updateQuery. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * @param int $id table id * * @return object */ public function update(array $params, int $id): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setUpdateArray([ 'fieldTest1', 'fieldTest2:fk=classNameFk', //foreign key ], $params, $id); } /** * Method to update. * Returns total of records affected. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return int */ public function updateQuery(array $params): int { return $this->mainUpdateQuery(function () use ($params) { $this->setUpdateArrayQuery([ 'fieldTest1', 'fieldTest2', ], $params); }); } /*------------------------------------------------------------------------------------- * SELECTS *-------------------------------------------------------------------------------------*/ /** * Settings select. * All the data from the table. */ public function selectAll() { //select $this->select("ug, {$this->mAlias}"); $this->from(); //joins $this->innerJoinUserGenre(); //set results (optional) - more information see the documentation. //$this->setQueryResultFormat('getResult'); //set hidration (optional) - more information see the documentation. //$this->addHydrateObject(); //$this->addCustomHydrationMode('ObjectAndScalarHydrator'); //$this->setReturn('doctrine'); //optional - default: array } /*------------------------------------------------------------------------------------- * JOINS *-------------------------------------------------------------------------------------*/ /** * Inner join UserGenre. */ private function innerJoinUserGenre() { $this->innerJoin("{$this->mAlias}.userGenre", 'ug'); } /*------------------------------------------------------------------------------------- * WHERES *-------------------------------------------------------------------------------------*/ /** * Where field u.id = ? * * @param int $value */ public function whereIdEq(int $value) { return $this->expr('id', '=', $value); } /*------------------------------------------------------------------------------------- * ORDERS BYS *-------------------------------------------------------------------------------------*/ /** * Sort by field u.id * * @param string $value DESC | ASC */ public function orderId(string $value = 'DESC') { $this->addOrderBy('id', $value); } /*------------------------------------------------------------------------------------- * GROUPS BYS *-------------------------------------------------------------------------------------*/ /** * Group by field u.id */ public function groupById() { $this->addGroupBy('id'); } /*------------------------------------------------------------------------------------- * HAVINGS *-------------------------------------------------------------------------------------*/ /** * Having field u.id = ? * * @param int $value */ public function havingIdEq(int $value) { return $this->expr('id', '=', $value); } /*------------------------------------------------------------------------------------- * DQL *-------------------------------------------------------------------------------------*/ //Dql methods here // }
示例接口仓库
文件: app/Repositories/User/UserRepositoryInterface.php
<?php /** * User repository interface. * * Code generated by cli command. * * @see http://github.com/fernandozueet/laravel-doctrine-repository * * @copyright 2018 */ namespace App\Repositories\User; interface UserRepositoryInterface { /*------------------------------------------------------------------------------------- * OTHERS *-------------------------------------------------------------------------------------*/ //Others here // public function whereIdEq(int $value); public function orderId(string $value = 'DESC'); public function groupById(); public function havingIdEq(int $value); /*------------------------------------------------------------------------------------- * GENERAL *-------------------------------------------------------------------------------------*/ public function create(array $params): object; public function update(array $params, int $id): object; public function updateQuery(array $params): int; public function selectAll(); public function setTransaction($conn); public function beginTransaction(); public function commitTransaction(); public function rollBackTransaction(); public function find(int $id, string $typeTreat = '', array $treatObject = []): object; public function createQuery(); public function setQuery($query); public function getQuery(); public function readQuery(string $typeTreat = '', array $treatObject = []): object; public function paginator(int $firstResult, int $limit); public function setMaxResults(int $limit); public function orderByRand(); public function setWhere($param); public function setAndWhere($param); public function setOrWhere($param); public function setCondOrWhere(); public function setCondAndWhere(); public function setCondNotWhere(); public function setParentStartWhere(); public function setParentEndWhere(); public function whereExpr($function); public function setHaving($param); public function setAndHaving($param); public function setOrHaving($param); public function setCondOrHaving(); public function setCondAndHaving(); public function setCondNotHaving(); public function setParentStartHaving(); public function setParentEndHaving(); public function havingExpr($function); public function deleteQuery(): bool; }
示例类服务提供者
文件: app/Providers/UserDocRepositoryServiceProvider.php
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class UserDocRepositoryServiceProvider extends ServiceProvider { /** * Bootstrap services. * * @return void */ public function boot() { // } /** * Register services. * * @return void */ public function register() { $this->app->bind('\App\Repositories\User\UserRepositoryInterface', function ($app) { return new \App\Repositories\User\UserDocRepository(); }); } }
使用不同的数据库连接
在 config/doctrine.php 文件的 managers 数组中配置新的配置,您可能会注意到默认连接名称为 default。在数组中插入新的位置并设置配置
'managers' => [ 'default' => [ //..... ], 'otherConnection' => [ //----------------------------------------------- //Laravel doctrine repository config //----------------------------------------------- 'LdrConfig' => [ 'namespaceEntities' => 'App\Entities', ], //----------------------------------------------- 'dev' => env('APP_DEBUG', false), 'meta' => env('DOCTRINE_METADATA', 'annotations'), 'connection' => env('DB_CONNECTION', 'mysql'), 'namespaces' => [], 'paths' => [ base_path('app\Entities'), ], 'repository' => Doctrine\ORM\EntityRepository::class, 'proxies' => [ 'namespace' => false, 'path' => storage_path('proxies'), 'auto_generate' => env('DOCTRINE_PROXY_AUTOGENERATE', true), ], /* |-------------------------------------------------------------------------- | Doctrine events |-------------------------------------------------------------------------- | | The listener array expects the key to be a Doctrine event | e.g. Doctrine\ORM\Events::onFlush | */ 'events' => [ 'listeners' => [], 'subscribers' => [], ], 'filters' => [], /* |-------------------------------------------------------------------------- | Doctrine mapping types |-------------------------------------------------------------------------- | | Link a Database Type to a Local Doctrine Type | | Using 'enum' => 'string' is the same of: | $doctrineManager->extendAll(function (\Doctrine\ORM\Configuration $configuration, | \Doctrine\DBAL\Connection $connection, | \Doctrine\Common\EventManager $eventManager) { | $connection->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); | }); | | References: | http://doctrine-orm.readthedocs.org/en/latest/cookbook/custom-mapping-types.html | http://doctrine-dbal.readthedocs.org/en/latest/reference/types.html#custom-mapping-types | http://doctrine-orm.readthedocs.org/en/latest/cookbook/advanced-field-value-conversion-using-custom-mapping-types.html | http://doctrine-orm.readthedocs.org/en/latest/reference/basic-mapping.html#reference-mapping-types | https://symfony.com.cn/doc/current/cookbook/doctrine/dbal.html#registering-custom-mapping-types-in-the-schematool |-------------------------------------------------------------------------- */ 'mapping_types' => [ //'enum' => 'string' ], ], ]
在仓库中使用新的连接
文件: app/Repositories/User/UserDocRepository.php
public function __construct() { parent::__construct('otherConnection'); //set new connection here $this->main($this->fkEntities, $this->mAlias, __CLASS__); }
实例化创建的仓库
您可以在控制器、服务层或任何您想要的位置使用仓库。
如果您已使用接口创建仓库。
1 - 直接实例化
$userRepository = app('\App\Repositories\User\UserRepositoryInterface');
2 - 使用控制器
/** * User repository * * @var \App\Repositories\User\UserRepositoryInterface */ private $userRepository; /** * Construct. * * @return void */ public function __construct(\App\Repositories\User\UserRepositoryInterface $userRepository) { $this->userRepository = $userRepository; }
如果您没有创建接口。
1 - 直接实例化
$userRepository = app('\App\Repositories\User\UserDocRepository'); //or $userRepository = new \App\Repositories\User\UserDocRepository();
2 - 使用控制器
/** * User repository * * @var \App\Repositories\User\UserDocRepository */ private $userRepository; /** * Construct. * * @return void */ public function __construct() { $this->userRepository = app('\App\Repositories\User\UserDocRepository'); //or $this->userRepository = new \App\Repositories\User\UserDocRepository(); }
插入数据 (INSERT)
示例表: id、first_name、lastName、user_genre_id、updated_at、created_at。
created_at 自动插入。
文件: app/Repositories/User/UserDocRepository.php
/** * Method of insertion in the database. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return object */ public function create(array $params): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setCreateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params); }
不自动插入 createdAt
/** * Method of insertion in the database. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return object */ public function create(array $params): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setCreateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, false); }
处理返回的对象
/** * Method of insertion in the database. * Returns the created object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return object */ public function create(array $params): object { //$this->setReturn('doctrine'); //optional - default: array //Ex 1: The return object will return only the firstName and lastName fields return $this->setCreateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, true, 'included', ['firstName','lastName']); //Ex 2: The return object will not return the firstName and lastName fields return $this->setCreateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, true, 'excluded', ['firstName','lastName']); }
执行函数
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //insert $res = $userRepository->create([ 'firstName' => 'Alex', 'lastName' => 'Silva', 'userGenre' => 1 ]); //Returns the object. var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
更新数据 (UPDATE)
示例表: id、first_name、lastName、user_genre_id、updated_at、created_at。
updated_at 自动更新。
注意! 要更新多个数据,请使用 updateQuery 方法。
文件: app/Repositories/User/UserDocRepository.php
/** * Method to update. To update more than one data, use the method updateQuery. * Returns the object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * @param int $id table id * * @return object */ public function update(array $params, int $id): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setUpdateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, $id); }
不自动更新 updatedAt
/** * Method to update. To update more than one data, use the method updateQuery. * Returns the object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * @param int $id table id * * @return object */ public function update(array $params, int $id): object { //$this->setReturn('doctrine'); //optional - default: array return $this->setUpdateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, $id, false); }
处理返回的对象
/** * Method to update. To update more than one data, use the method updateQuery. * Returns the object. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * @param int $id table id * * @return object */ public function update(array $params, int $id): object { //$this->setReturn('doctrine'); //optional - default: array //Ex 1: The return object will return only the firstName and lastName fields return $this->setUpdateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, $id, true, 'included', ['firstName','lastName']); //Ex 2: The return object will not return the firstName and lastName fields return $this->setUpdateArray([ 'firstName', 'lastName', 'userGenre:fk=UserGenre', //foreign key ], $params, $id, true, 'excluded', ['firstName','lastName']); }
执行函数
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //update $res = $userRepository->update([ 'firstName' => 'Alex 2', 'lastName' => 'Silva 2', 'userGenre' => 2 ], 1); //Returns the object var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
更新查询数据 (UPDATE)
示例表: id、first_name、lastName、user_genre_id、updated_at、created_at。
updated_at 自动更新。
文件: app/Repositories/User/UserDocRepository.php
/** * Method to update. * Returns total of records affected. * * @param array $params Use the same naming convention as the database attribute. In camel case. Ex: firstName * * @return int */ public function updateQuery(array $params): int { return $this->mainUpdateQuery(function () use ($params) { //set individual $this->set('firstName', $params['firstName']); //set json mysql $this->setJsonReplace('name', 'firstName', $params['firstName']); $this->setJsonSet('name', 'firstName', $params['firstName']); $this->setJsonInsert('name', 'firstName', $params['firstName']); //set all array $this->setUpdateArrayQuery([ 'firstName', 'lastName', 'userGenre', ], $params); //Do not automatically update updatedAt $this->setUpdateArrayQuery([ 'firstName', 'lastName', 'userGenre', ], $params, false); }); }
创建更新条件
/*------------------------------------------------------------------------------------- * WHERES *-------------------------------------------------------------------------------------*/ /** * Where field u.id = ? * * @param int $value */ public function whereIdEq(int $value) { return $this->expr('id', '=', $value); }
执行函数
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //start query $userRepository->createQuery(); //where $userRepository->whereExpr(function () use ($userRepository) { //where id = 17 $userRepository->setWhere($userRepository->whereIdEq(17)); //add more conditions here // }); //update $res = $userRepository->updateQuery([ 'firstName' => 'Alex 2', 'lastName' => 'Silva 2', 'userGenre' => 2 ], 1); //total of records affected var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
删除数据 (DELETE)
创建删除条件
文件: app/Repositories/User/UserDocRepository.php
/*------------------------------------------------------------------------------------- * WHERES *-------------------------------------------------------------------------------------*/ /** * Where field u.id = ? * * @param int $value */ public function whereIdEq(int $value) { return $this->expr('id', '=', $value); }
执行函数
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //start query $userRepository->createQuery(); //where $userRepository->whereExpr(function () use ($userRepository) { //where id = 17 $userRepository->setWhere($userRepository->whereIdEq(17)); //add more conditions here // }); //delete $res = $userRepository->deleteQuery(); //returned boolean var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
选择数据 (SELECT)
选择设置
文件: app/Repositories/User/UserDocRepository.php
/*------------------------------------------------------------------------------------- * CONFIGS *-------------------------------------------------------------------------------------*/ /** * Foreign key entities names. * * @var array */ private $fkEntities = ['UserGenre']; /** * Main alias. * * @var string */ private $mAlias = 'u'; /*------------------------------------------------------------------------------------- * SELECTS *-------------------------------------------------------------------------------------*/ /** * Settings select. * All the data from the table. */ public function selectAll() { //select $this->select("ug, {$this->mAlias}"); //brings all the data //$this->select("{$this->mAlias}.id, {$this->mAlias}.firsName, {$this->mAlias}.lastName, ug.id, ug.desc"); //brings specific data //$this->select("{$this->mAlias}, PARTIAL ug.{id, desc}"); //add result getArrayResult //$this->addSelect("ug"); //add select several lines $this->from(); //joins $this->innerJoinUserGenre(); //set results (optional) //$this->setQueryResultFormat('getResult'); //$this->setQueryResultFormat('getArrayResult'); //$this->setQueryResultFormat('getSingleResult'); //$this->setQueryResultFormat('getOneOrNullResult'); //$this->setQueryResultFormat('getScalarResult'); //$this->setQueryResultFormat('getSingleScalarResult'); //set hidration (optional) //$this->addHydrateObject(); //$this->addHydrateArray(); //$this->addHydrateScalar(); //$this->addHydrateSingleScalar(); //$this->addCustomHydrationMode('ObjectAndScalarHydrator'); //$this->addCustomHydrationMode('ArrayHydratorCustom'); //$this->setReturn('doctrine'); //optional - default: array } /*------------------------------------------------------------------------------------- * JOINS *-------------------------------------------------------------------------------------*/ /** * Inner join UserLocate. */ private function innerJoinUserGenre() { $this->innerJoin("{$this->mAlias}.userGenre", 'ug'); //or //$this->innerJoin('UserGenre', 'ug', 'WITH', "ug.id = {$this->mAlias}.userGenre"); } /** * Left join UserLocate. */ private function leftJoinUserGenre() { $this->leftJoin("{$this->mAlias}.userGenre", 'ug'); //or //$this->leftJoin('UserGenre', 'ug', 'WITH', "ug.id = {$this->mAlias}.userGenre"); } /** * Join UserLocate. */ private function joinUserGenre() { $this->join("{$this->mAlias}.userGenre", 'ug'); //or //$this->join('UserGenre', 'ug', 'WITH', "ug.id = {$this->mAlias}.userGenre"); }
创建选择条件
/*------------------------------------------------------------------------------------- * WHERES *-------------------------------------------------------------------------------------*/ /** * Where field u.id = ? * * @param int $value */ public function whereIdEq(int $value) { return $this->expr('id', '=', $value); }
创建选择排序
/*------------------------------------------------------------------------------------- * ORDERS BYS *-------------------------------------------------------------------------------------*/ /** * Sort by field u.id * * @param string $value DESC | ASC */ public function orderId(string $value = 'DESC') { $this->addOrderBy('id', $value); }
创建选择分组
/*------------------------------------------------------------------------------------- * GROUPS BYS *-------------------------------------------------------------------------------------*/ /** * Group by field u.id */ public function groupById() { $this->addGroupBy('id'); }
创建选择分组条件
/*------------------------------------------------------------------------------------- * HAVINGS *-------------------------------------------------------------------------------------*/ /** * Having field u.id = ? * * @param int $value */ public function havingIdEq(int $value) { return $this->expr('id', '=', $value); }
执行函数
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //start query $userRepository->createQuery(); //settings select $userRepository->selectAll(); //where (optional) $userRepository->whereExpr(function () use ($userRepository) { //where id = 17 $userRepository->setWhere($userRepository->whereIdEq(17)); //where functions //$userRepository->setAndWhere($userRepository->whereFirstNameEq('Alex')); // AND firstName = 'alex' //$userRepository->setOrWhere($userRepository->whereFirstNameEq('Alex')); // OR firstName = 'alex' //$userRepository->setCondAndWhere(); // AND //$userRepository->setCondOrWhere(); // OR //$userRepository->setCondNotWhere(); // NOT //$userRepository->setParentStartWhere(); // ( //$userRepository->setParentEndWhere(); // ) //add more conditions here // }); //having (optional) $userRepository->havingExpr(function () use ($userRepository) { //having id = 17 $userRepository->setHaving($userRepository->havingIdEq(17)); //where functions //$userRepository->setAndHaving($userRepository->havingFirstNameEq('Alex')); // AND firstName = 'alex' //$userRepository->setOrHaving($userRepository->havingFirstNameEq('Alex')); // OR firstName = 'alex' //$userRepository->setCondAndHaving(); // AND //$userRepository->setCondOrHaving(); // OR //$userRepository->setCondOrHaving(); // NOT //$userRepository->setParentStartHaving(); // ( //$userRepository->setParentEndHaving(); // ) //add more conditions here // }); //order by (optional) $userRepository->orderId('ASC'); //order by rand (optional) $userRepository->orderByRand(); //group by (optional) $userRepository->groupById(); //max results (optional) $userRepository->setMaxResults(1); //paginator (optional) $userRepository->paginator(0, 1); //results - original result $res = $userRepository->readQuery(); //results - will return only the firstName and lastName fields. //Works only when all data is returned and no setQueryResultFormat is set. $res = $userRepository->readQuery('included', ['firstName','lastName']); //results - will not return the firstName and lastName fields. //Works only when all data is returned and no setQueryResultFormat is set. $res = $userRepository->readQuery('excluded', ['firstName','lastName']); //returned results var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
按 ID 查找
执行函数
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //find $res = $userRepository->find(36); //or //find - will return only the firstName and lastName fields. $res = $userRepository->find(36, 'included', ['firstName','lastName']); //or //find - will not return the firstName and lastName fields. $res = $userRepository->find(36, 'excluded', ['firstName','lastName']); //returned results var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
事务
执行函数
$userGenre = app('\App\Repositories\UserGenre\UserGenreRepositoryInterface'); $userRepository = app('\App\Repositories\User\UserRepositoryInterface'); //init transaction $transaction = $userGenre->beginTransaction(); //----------------------- //insert userGenre try { //set transaction $userGenre->setTransaction($transaction); //insert $res = $userGenre->create([ 'desc' => 'woman' ]); } catch (\Exception $e) { //rollBack $userGenre->rollBackTransaction(); //error return $e->getMessage(); } //----------------------- //insert user try { //setTransaction $userRepository->setTransaction($transaction); //insert $res = $userRepository->create([ 'firstName' => 'Alex', 'lastName' => 'Silva', 'userGenre' => $res->id ]); } catch (\Exception $e) { //rollBack $userRepository->rollBackTransaction($transaction); //error return $e->getMessage(); } //commit data $userGenre->commitTransaction();
Dql
创建查询
文件: app/Repositories/User/UserDocRepository.php
/*------------------------------------------------------------------------------------- * DQL *-------------------------------------------------------------------------------------*/ /** * Select with dql. * * @param array $params * @return object */ public function selectDql(array $params): object { $this->createQueryDql("SELECT u FROM {$this->entityMain} AS u WHERE u.id = ?0"); //dql query $this->setParameterDql(0, $params['id']); //set parameter $this->paginatorDql($params['firstResult'], $params['maxResults']); //paginator //$this->setReturn('doctrine'); //optional - default: array //result return $this->getResultDql(); //or //result - will return only the firstName and lastName fields. return $this->getResultDql('included', ['firstName','lastName']); //or //find - will not return the firstName and lastName fields. return $this->getResultDql('excluded', ['firstName','lastName']); }
执行函数
$userRepository = app('\App\Repositories\User\UserRepositoryInterface'); try { //dql select $res = $userRepository->selectDql([ 'id' => 1, 'firstResult' => 0, 'maxResults' => 5 ]); //returned results var_dump($res); } catch (\Exception $e) { //error return $e->getMessage(); }
WHERE 和 HAVING 选项
以下选项适用于WHERE和HAVING。
文件: app/Repositories/User/UserDocRepository.php
/** * Where field u.id = ? * * @param int $id */ public function whereIdEq(int $id) { return $this->expr('id', '=', $id); } /** * Where field json u.name.firstname LIKE ? * * @param string $value */ public function whereNameFirstNameLike(string $value) { return $this->expr($this->fieldJson('name', 'firstName'), 'LIKE', "%$value%", false); } /** * Where field ug.id = ? * * @param int $id */ public function whereUserGenreIdEq(int $id) { return $this->expr('ug.id', '=', $id, false); } /** * Where field u.id > ? * * @param int $id */ public function whereIdGt(int $id) { return $this->expr('id', '>', $id); } /** * Where field u.id >= ? * * @param int $id */ public function whereIdGte(int $id) { return $this->expr('id', '>=', $id); } /** * Where field u.id < ? * * @param int $id */ public function whereIdLt(int $id) { return $this->expr('id', '<', $id); } /** * Where field u.id <= ? * * @param int $id */ public function whereIdLte(int $id) { return $this->expr('id', '<=', $id); } /** * Where field u.id <> ? * * @param int $id */ public function whereIdNeq(int $id) { return $this->expr('id', '<>', $id); } /** * Where field u.id IS NULL */ public function whereIdIsNull() { return $this->expr('id', 'IS NULL', ''); } /** * Where field u.id IS NOT NULL */ public function whereIdIsNotNull() { return $this->expr('id', 'IS NOT NULL', ''); } /** * Where field u.id * ? * * @param int $id */ public function whereIdProd(int $id) { return $this->expr('id', '*', $id); } /** * Where field u.id - ? * * @param int $id */ public function whereIdDiff(int $id) { return $this->expr('id', '-', $id); } /** * Where field u.id + ? * * @param int $id */ public function whereIdSum(int $id) { return $this->expr('id', '+', $id); } /** * Where field u.id / ? * * @param int $id */ public function whereIdQuot(int $id) { return $this->expr('id', '/', $id); } /** * Where field u.id IN (?,?,?,...) * * @param array $values */ public function whereIdIn(array $values) { return $this->expr('id', 'IN', $values); } /** * Where field u.id NOT IN (?,?,?,...) * * @param array $values */ public function whereIdNotIn(array $values) { return $this->expr('id', 'NOT IN', $values); } /** * Where field u.firstName LIKE ? * * @param string $value */ public function whereFirstNameLike(string $value) { return $this->expr('firstName', 'LIKE', "%$value%"); } /** * Where field u.firstName NOT LIKE ? * * @param string $value */ public function whereFirstNameNotLike(string $value) { return $this->expr('firstName', 'NOT LIKE', "%$value%"); } /** * Where field u.createdAt BETWEEN ? AND ? * * @param string $value1 * @param string $value2 * @return void */ public function whereCreatedAtBetween(string $value1, string $value2) { return $this->expr('createdAt', '', $this->exprBetween($value1, $value2), true, false); } /** * Where field u.createdAt NOT BETWEEN ? AND ? * * @param string $value1 * @param string $value2 * @return void */ public function whereCreatedAtNotBetween(string $value1, string $value2) { return $this->expr('createdAt', 'NOT', $this->exprBetween($value1, $value2), true, false); }
ORDER BY 选项
文件: app/Repositories/User/UserDocRepository.php
/** * Sort by field u.id * * @param string $value DESC | ASC */ public function orderId(string $value = 'DESC') { $this->addOrderBy('id', $value); } /** * Sort by field ug.id * * @param string $value DESC | ASC */ public function orderUserGenreId(string $value = 'DESC') { $this->addOrderBy('ug.id', $value, false); }
GROUP BY 选项
文件: app/Repositories/User/UserDocRepository.php
/** * Group by field u.id */ public function groupById() { $this->addGroupBy('id'); } /** * Group by field ug.id */ public function groupByUserGenreId() { $this->addGroupBy('ug.id', false); }
额外函数
文件: app/Repositories/User/UserDocRepository.php
//principal entity namespace (string) var_dump($this->entityMain);
//namespaces of entities (array) var_dump($this->ent);
//principal entity name (string) var_dump($this->mainNameEntity);
//search entity (string) var_dump($this->searchEnt('UserGenre'));
//get reference $this->getReference("UserGenre", $id);
//persist $this->persist($entity);
//flush $this->flush();
//clear $this->clear();
//json extract mysql - name.firstName $this->fieldJson('name', 'firstName');
//created name parameter. //will pass the die to bind :dc_value1 $this->createNamedParameter($params['firstName']);
贡献
有关详细信息,请参阅贡献指南。
安全性
如果您发现与安全相关的问题,请通过电子邮件fernandozueet@hotmail.com联系,而不是使用问题跟踪器。
致谢
许可证
PHP上传和图像处理项目遵循MIT许可证。有关更多信息,请参阅许可证文件。