Complete repository model with laravel doctrine
fernandozueet/laravel-doctrine-repository is a Laravel package for complete repository model with laravel doctrine.
It currently has 1 GitHub stars and 116 downloads on Packagist (latest version 1.4.2).
Install it with composer require fernandozueet/laravel-doctrine-repository.
Discover more Laravel packages by fernandozueet
or browse all Laravel packages to compare alternatives.
Last updated
Complete repository model with laravel doctrine.
The doctrine laravel library is used as the base of the repository class. Documentation of lib laravel doctrine
Install this package with composer:
composer require fernandozueet/laravel-doctrine-repository
After updating composer, add the ServiceProvider to the providers array in config/app.php
Ldr\Core\DoctrineRepositoryServiceProvider::class,
To publish the config use:
php artisan vendor:publish --tag="configRepository"
1- Configure your connection to the database .env
2- Configure extra doctrine information. config/doctrine.php
3- Generate the entities
php artisan make:doctrine-repository:entities
4- Generate repository file.
File will be created by default app/Repositories folder. You can change the folder in the config/doctrine.php file.
ATTENTION!! use the same entity name
php artisan make:doctrine-repository User
Create file inside a folder
php artisan make:doctrine-repository SubPath/User
file: 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
//
}
file: 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;
}
file: 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();
});
}
}
Configure the new configuration in managers array the config/doctrine.php file you may notice that the default connection name is default. Insert a new position in the array with the settings
'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
| http://symfony.com/doc/current/cookbook/doctrine/dbal.html#registering-custom-mapping-types-in-the-schematool
|--------------------------------------------------------------------------
*/
'mapping_types' => [
//'enum' => 'string'
],
],
]
Using the new connection in the repository:
file: app/Repositories/User/UserDocRepository.php
public function __construct()
{
parent::__construct('otherConnection'); //set new connection here
$this->main($this->fkEntities, $this->mAlias, __CLASS__);
}
You can use the repository in your controller, service layer or wherever you want.
If you have created the repository with interface.
1 - Instantiating directly:
$userRepository = app('\App\Repositories\User\UserRepositoryInterface');
2 - Use controller:
/**
* User repository
*
* @var \App\Repositories\User\UserRepositoryInterface
*/
private $userRepository;
/**
* Construct.
*
* @return void
*/
public function __construct(\App\Repositories\User\UserRepositoryInterface $userRepository)
{
$this->userRepository = $userRepository;
}
if you have not created an interface.
1 - Instantiating directly:
$userRepository = app('\App\Repositories\User\UserDocRepository');
//or
$userRepository = new \App\Repositories\User\UserDocRepository();
2 - Use controller:
/**
* 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();
}
example table: id, first_name, lastName, user_genre_id, updated_at, created_at.
created_at automatically inserted.
file: 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);
}
Do not automatically inserted 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);
}
Dealing with the object of return:
/**
* 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']);
}
Execute function:
$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();
}
example table: id, first_name, lastName, user_genre_id, updated_at, created_at.
updated_at automatically update.
ATTENTION! To update more than one data, use the method updateQuery.
file: 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);
}
Do not automatically update 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);
}
Dealing with the object of return:
/**
* 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']);
}
Execute function:
$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();
}
example table: id, first_name, lastName, user_genre_id, updated_at, created_at.
updated_at automatically update.
file: 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);
});
}
Creating the condition for the update:
/*-------------------------------------------------------------------------------------
* WHERES
*-------------------------------------------------------------------------------------*/
/**
* Where field u.id = ?
*
* @param int $value
*/
public function whereIdEq(int $value)
{
return $this->expr('id', '=', $value);
}
Execute function:
$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();
}
Creating the condition for the delete:
file: app/Repositories/User/UserDocRepository.php
/*-------------------------------------------------------------------------------------
* WHERES
*-------------------------------------------------------------------------------------*/
/**
* Where field u.id = ?
*
* @param int $value
*/
public function whereIdEq(int $value)
{
return $this->expr('id', '=', $value);
}
Execute function:
$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 settings:
file: 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");
}
Creating the condition for the select:
/*-------------------------------------------------------------------------------------
* WHERES
*-------------------------------------------------------------------------------------*/
/**
* Where field u.id = ?
*
* @param int $value
*/
public function whereIdEq(int $value)
{
return $this->expr('id', '=', $value);
}
Creating the order by for the select:
/*-------------------------------------------------------------------------------------
* ORDERS BYS
*-------------------------------------------------------------------------------------*/
/**
* Sort by field u.id
*
* @param string $value DESC | ASC
*/
public function orderId(string $value = 'DESC')
{
$this->addOrderBy('id', $value);
}
Creating the group by for the select:
/*-------------------------------------------------------------------------------------
* GROUPS BYS
*-------------------------------------------------------------------------------------*/
/**
* Group by field u.id
*/
public function groupById()
{
$this->addGroupBy('id');
}
Creating the having for the select:
/*-------------------------------------------------------------------------------------
* HAVINGS
*-------------------------------------------------------------------------------------*/
/**
* Having field u.id = ?
*
* @param int $value
*/
public function havingIdEq(int $value)
{
return $this->expr('id', '=', $value);
}
Execute function:
$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();
}
Execute function:
$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();
}
Execute function:
$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();
Creating query:
file: 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']);
}
Execute function:
$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();
}
These options are valid for where and having.
file: 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);
}
file: 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);
}
file: 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);
}
file: 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']);
Please see CONTRIBUTING for details.
If you discover security related issues, please email [email protected] instead of using the issue tracker.
The PHP Upload and Image Manipulation is licensed under the MIT license. See License File for more information.