My entity :
class User{
id : int
name : string
boss : User()
}
I want to create a function that return an array() of users that work under a giving user.
example :
public function MyEmployers( User $user , array $usersList )
{
$myEmployers = array();
...
return $myEmployers;
}
$results = $this->myEmployers ( $employer1 , $allEmployers)
dump ( $results );
$results = [ 4 , 5 , 6 ];
I found a solution if someone can improve it feel free :
public $tree = array();
public function MyEmployers(User $user)
{
$superior_key_id = array();
$all_users = $this->getallusers();
$id = $user->getId();
foreach ($all_users as $user) {
if ($user->getSuperior())
$superior_key_id[$user->getSuperior()->getId()][] = $user;
}
$this->getSubEmployee($this->getUser(), $superior_key_id);
return ($this->tree);
}
public function getSubEmployee($user, $superior_key_id)
{
if (isset($superior_key_id[$user->getId()])) {
foreach ($superior_key_id[$user->getId()] as $user) {
$this->tree[] = $user;
$this->getSubEmployee($user, $superior_key_id);
}
}
return $user;
}
this one will get all bosses if you're interested :
public function MyBosses(User $user)
{
$bosses = array();
while ($user->getSuperior()) {
array_push($bosses, $user->getSuperior());
$user = $user->getSuperior();
}
return $bosses;
}
You could set up a one-to-many relationship between boss and employee
So you're user class could look like:
class User{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="employee")
*/
private $boss;
/**
* #ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="boss")
*/
private $employees;
public function __construct()
{
$this->employees = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|employees[]
*/
public function getEmployees(): Collection
{
return $this->employees;
}
public function addEmployee(employee $employee): self
{
if (!$this->employees->contains($employee)) {
$this->employees[] = $employee;
}
return $this;
}
public function removeEmployee(employee $employee): self
{
if ($this->employees->contains($employee)) {
$this->employees->removeElement($employee);
}
return $this;
}
public function getBoss(): ?Usesr
{
return $this->boss;
}
public function setBoss(?User $boss): self
{
$this->boss = $boss;
return $this;
}
}
You would need to set up the database relationship with the symfony make:entity command.
To get all employeers under a user, you could do something like:
function getAllEmployeesUnder(User $user)
{
$allEmployees = [];
foreach ($user->getEmployees as $employee) {
$allEmployees[] = $employee;
$allEmployees = array_merge($allEmployees, $this->getAllEmployeesUnder($employee));
}
return $allEmployees;
}
Related
My Entity Item has a Repository (ItemRepository) with the function findItemCount(). When I use
$repository = $em->getRepository(Item::class);
$items = $repository->findItemCount();
I get the warning:
Potentially polymorphic call. The code may be inoperable depending on the actual class instance passed as the argument.
Also the auto completion doesn't suggest me the function "findItemCount". What is my mistake?
Controller:
/**
* Artikel Liste
* #Route("/item/list", name="app_item_list")
* #param EntityManagerInterface $em
* #return Response
*/
public function listItems(EntityManagerInterface $em): Response
{
$repository = $em->getRepository(Item::class);
$items = $repository->findItemCount();
return $this->render('item_admin/itemList.html.twig', [
'items' => $items,
'title' => 'Artikel Übersicht',
'blocked' => false
]);
}
Item.php
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\OrderBy;
/**
* #ORM\Entity(repositoryClass="App\Repository\ItemRepository")
*/
class Item
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #OrderBy({"name" = "ASC"})
*/
private $name;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Itemparent", inversedBy="item")
*/
private $itemparent;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Itemgroup", inversedBy="items")
*/
private $itemgroup;
/**
* #ORM\Column(type="string", length=255)
*/
private $minsize;
/**
* #ORM\Column(type="boolean")
*/
private $charge;
/**
* #ORM\Column(type="boolean")
*/
private $blocked;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Barcode", mappedBy="item", orphanRemoval=true)
*/
private $barcodes;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ItemStock", mappedBy="item", orphanRemoval=true)
*/
private $itemStocks;
/**
* #ORM\OneToMany(targetEntity="App\Entity\BookingItem", mappedBy="item", orphanRemoval=true)
*/
private $bookingItems;
/**
* #ORM\Column(type="float", nullable=true)
*/
private $price;
/**
* #ORM\OneToMany(targetEntity=SupplierItems::class, mappedBy="item")
*/
private $supplierItems;
/**
* #ORM\OneToMany(targetEntity=ItemStockCharge::class, mappedBy="item")
*/
private $itemStockCharges;
public function __construct()
{
$this->barcodes = new ArrayCollection();
$this->itemStocks = new ArrayCollection();
$this->suppliers = new ArrayCollection();
$this->supplierItems = new ArrayCollection();
$this->itemStockCharges = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getItemparent(): ?Itemparent
{
return $this->itemparent;
}
public function setItemparent(?Itemparent $itemparent): self
{
$this->itemparent = $itemparent;
return $this;
}
public function getItemgroup(): ?Itemgroup
{
return $this->itemgroup;
}
public function setItemgroup(?Itemgroup $itemgroup): self
{
$this->itemgroup = $itemgroup;
return $this;
}
public function getMinsize(): ?string
{
return $this->minsize;
}
public function setMinsize(string $minsize): self
{
$this->minsize = $minsize;
return $this;
}
public function getCharge(): ?bool
{
return $this->charge;
}
public function setCharge(bool $charge): self
{
$this->charge = $charge;
return $this;
}
public function getBlocked(): ?bool
{
return $this->blocked;
}
public function setBlocked(bool $blocked): self
{
$this->blocked = $blocked;
return $this;
}
/**
* #return Collection|Barcode[]
*/
public function getBarcodes(): Collection
{
return $this->barcodes;
}
public function addBarcode(Barcode $barcode): self
{
if (!$this->barcodes->contains($barcode)) {
$this->barcodes[] = $barcode;
$barcode->setItem($this);
}
return $this;
}
public function removeBarcode(Barcode $barcode): self
{
if ($this->barcodes->contains($barcode)) {
$this->barcodes->removeElement($barcode);
// set the owning side to null (unless already changed)
if ($barcode->getItem() === $this) {
$barcode->setItem(null);
}
}
return $this;
}
/**
* #return Collection|ItemStock[]
*/
public function getItemStocks(): Collection
{
return $this->itemStocks;
}
public function addItemStock(ItemStock $itemStock): self
{
if (!$this->itemStocks->contains($itemStock)) {
$this->itemStocks[] = $itemStock;
$itemStock->setItem($this);
}
return $this;
}
public function removeItemStock(ItemStock $itemStock): self
{
if ($this->itemStocks->contains($itemStock)) {
$this->itemStocks->removeElement($itemStock);
// set the owning side to null (unless already changed)
if ($itemStock->getItem() === $this) {
$itemStock->setItem(null);
}
}
return $this;
}
/**
* #return Collection|BookingItem[]
*/
public function getBookingItems(): Collection
{
return $this->bookingItems;
}
public function addBookingItem(BookingItem $bookingItem): self
{
if (!$this->bookingItems->contains($bookingItem)) {
$this->bookingItems[] = $bookingItem;
$bookingItem->setItem($this);
}
return $this;
}
public function removeBookingItem(BookingItem $bookingItem): self
{
if ($this->bookingItems->contains($bookingItem)) {
$this->bookingItems->removeElement($bookingItem);
if ($bookingItem->getItem() === $this) {
$bookingItem->setItem(null);
}
}
return $this;
}
public function getPrice(): ?float
{
return $this->price;
}
public function setPrice(?float $price): self
{
$this->price = $price;
return $this;
}
public function getCommaPrice(): string
{
return number_format($this->price, 2, ',', '');
}
/**
* #return Collection|SupplierItems[]
*/
public function getSupplierItems(): Collection
{
return $this->supplierItems;
}
public function addSupplierItem(SupplierItems $supplierItem): self
{
if (!$this->supplierItems->contains($supplierItem)) {
$this->supplierItems[] = $supplierItem;
$supplierItem->setItem($this);
}
return $this;
}
public function removeSupplierItem(SupplierItems $supplierItem): self
{
if ($this->supplierItems->contains($supplierItem)) {
$this->supplierItems->removeElement($supplierItem);
// set the owning side to null (unless already changed)
if ($supplierItem->getItem() === $this) {
$supplierItem->setItem(null);
}
}
return $this;
}
/**
* #return Collection|ItemStockCharge[]
*/
public function getItemStockCharges(): Collection
{
return $this->itemStockCharges;
}
public function addItemStockCharge(ItemStockCharge $itemStockCharge): self
{
if (!$this->itemStockCharges->contains($itemStockCharge)) {
$this->itemStockCharges[] = $itemStockCharge;
$itemStockCharge->setItem($this);
}
return $this;
}
public function removeItemStockCharge(ItemStockCharge $itemStockCharge): self
{
if ($this->itemStockCharges->contains($itemStockCharge)) {
$this->itemStockCharges->removeElement($itemStockCharge);
// set the owning side to null (unless already changed)
if ($itemStockCharge->getItem() === $this) {
$itemStockCharge->setItem(null);
}
}
return $this;
}
}
ItemRepository.php
<?php
namespace App\Repository;
use App\Entity\Item;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
/**
* #method Item|null find($id, $lockMode = null, $lockVersion = null)
* #method Item|null findOneBy(array $criteria, array $orderBy = null)
* #method Item[] findAll()
* #method Item[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ItemRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Item::class);
}
public function findItem()
{
return $this->createQueryBuilder('a')
->andWhere('a.blocked = :val')
->setParameter('val', false)
->orderBy('a.name', 'ASC')
->getQuery()
->getResult()
;
}
public function findBlockedItemCount()
{
return $this->createQueryBuilder('item')
->select('item, SUM(stocks.count) as sums')
->andWhere('item.blocked = :val')
->setParameter('val', true)
->leftJoin('item.itemStocks', 'stocks')
->groupBy('item')
->orderBy('item.name', 'ASC')
->getQuery()
->getResult()
;
}
public function findItemCount(){
return $this->createQueryBuilder('item')
->select('item, SUM(stocks.count) as sums')
->andWhere('item.blocked = :val')
->setParameter('val', false)
->leftJoin('item.itemStocks', 'stocks')
->groupBy('item')
->orderBy('item.name', 'ASC')
->getQuery()
->getResult()
;
}
}
The IDE has now way of knowing that $em->getRepository(Item::class); will return ItemRepository, since that's not resolved until runtime.
Inject ItemRepository instead of the entity manager, it's the better practice in any case:
public function listItems(ItemRepository $itemRepository): Response
{
$items = $itemRepository->findItemCount();
// etc
}
I have a problem.. When I execute this code:
public function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
private static $users = $this->korisnici();
It gives me this error: syntax error, unexpected '$this' (T_VARIABLE)..
Can someone help me, how can I call this function?
Here's my whole class:
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $arr;
public function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
public $users = $this->korisnici();
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
I'm trying to change this default model from Yii Framework so I can login using database...
Looks like you have copied it from a class. The following will work like a regular function. Still not sure where you get $modelk = new Korisnici(); from
function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
print_r(korisnici());
EDIT: After looking at your whole class:
You need to use the __construct method.
public function __construct()
{
$this->users = $this->korisnici();
}
Can you help me? I can't understand how to join 2 and more tables, each table has the entity. Whether it is possible to use as in doctrine? I don't want to use doctrine.
How to join entities and use in views?
class User
{
protected $id;
protected $email;
protected $password;
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
}
public function setEmail($value)
{
$this->email = $value;
}
public function getEmail()
{
return $this->email;
}
public function setPassword($value)
{
$this->password = $value;
}
public function getPassword()
{
return $this->password;
}
}
class Info
{
protected $id;
protected $lastname;
protected $firstname;
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
}
public function setLastname($value)
{
$this->lastname = $value;
}
public function getLastname()
{
return $this->lastname;
}
public function setFirstname($value)
{
$this->firstname = $value;
}
public function getFirstname()
{
return $this->firstname;
}
}
class User
{
...
protected $info;
...
public function readInfo()
{
return $this->info;
}
public function writeInfo(Info $entity)
{
$this->info = $entity;
return $this;
}
}
class ModelUser
{
public function get()
{
$query = 'query for user with info';
$adapter = Zend\Db\TableGateway\Feature\GlobalAdapterFeature::getStaticAdapter();
$result = $adapter->query($query, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
/* Or use tableGateway */
/* Class methods hydrator */
$hydrator = new \Zend\Stdlib\Hydrator\ClassMethods;
/* Hydrate User entity from result */
$userEntity = $hydrator->hydrate($result->toArray(), new User);
/* Hydrate Info entity from result */
$infoEntity = $hydrator->hydrate($result->toArray(), new Info);
/* Write Info entity to User entity */
$userEntity->writeInfo($infoEntity);
return $userEntity;
}
}
class UserController
{
public function indexAction()
{
$model = new ModelUser();
$userEntity = $model->get();
return array(
'user' => $userEntity
);
}
}
I have two entities related Orders and Person where one Person can have many Orders. These are the mapping for that entities:
class Orders {
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="orders")
* #ORM\JoinColumn(name="person_id", referencedColumnName="id")
* */
protected $person;
public function setPerson(Person $person)
{
$this->person = $person;
return $this;
}
public function getPerson()
{
$this->person;
}
}
class Person {
/**
* #ORM\Column(name="person_type", type="boolean", nullable=false)
*/
protected $person_type = 1;
/**
* #ORM\OneToMany(targetEntity="NaturalPerson", mappedBy="person")
* */
private $naturals;
/**
* #ORM\OneToMany(targetEntity="LegalPerson", mappedBy="person")
* */
private $legals;
/**
* #ORM\OneToMany(targetEntity="Orders", mappedBy="person")
* */
private $orders;
public function __construct()
{
$this->naturals = new ArrayCollection();
$this->legals = new ArrayCollection();
$this->orders = new ArrayCollection();
}
public function setPersonType($person_type)
{
$this->person_type = $person_type;
return $this;
}
public function getPersonType()
{
return $this->person_type;
}
public function getNaturals()
{
return $this->naturals;
}
public function getLegals()
{
return $this->legals;
}
public function getOrders()
{
return $this->orders;
}
}
In my controller I'm trying to get from Orders the related record for Person but I'm getting NULL as the JSON shows:
{
"data":[
[
"sdasdasd",
null
],
[
"werwerwer",
null
],
[
"sdfsdfsf435435",
null
]
]
}
This is how I'm getting the data in controller:
public function getOrdersAction()
{
$response = array();
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository("FrontendBundle:Orders")->findAll();
$orders = array();
foreach ($entities as $entity)
{
$order = array();
$order[] = $entity->getNickname();
$order[] = $entity->getPerson();
$orders[] = $order;
}
$response['data'] = $orders;
return new JsonResponse($response);
}
I test values on DB tables by running this query:
SELECT ord.nickname, ord.person_id, pn.id, pn.description FROM orders ord left join person pn on pn.id = ord.person_id
And this is the result:
So records are related, then what I'm doing wrong?
Emmm... You just miss "return".
public function getPerson()
{
return $this->person;
}
I am having a model and would need to update the record. every time $count ($count = $post->save()) is being NULL. how is it possible to know whether this record saved or not. if saved, i want to display the following message 'Post updated' and if not the other message 'Post cannot update'.
This is always going to the else port. how can i know model updated correctly or not?
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$count = $post->save();
//var_dump($count); exit;
if ($count > 0) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
$this->_helper->flashMessenger->addMessage('Post cannot update');
}
Application_Model_Post code is as below,
class Application_Model_Post
{
/**
* #var int
*/
protected $_id;
/**
* #var string
*/
protected $_title;
/**
* #var string
*/
protected $_body;
/**
* #var string
*/
protected $_created;
/**
* #var string
*/
protected $_updated;
/**
* #var Application_Model_PostMapper
*/
protected $_mapper;
/**
* Class Constructor.
*
* #param array $options
* #return void
*/
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key=> $value) {
$method = 'set'.ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setId($id)
{
$this->_id = $id;
return $this;
}
public function getId()
{
return $this->_id;
}
public function setTitle($title)
{
$this->_title = (string) $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function setBody($body)
{
$this->_body = $body;
return $this;
}
public function getBody()
{
return $this->_body;
}
public function setCreated($ts)
{
$this->_created = $ts;
return $this;
}
public function getCreated()
{
return $this->_created;
}
/**
* Set data mapper.
*
* #param mixed $mapper
* #return Application_Model_Post
*/
public function setMapper($mapper)
{
$this->_mapper = $mapper;
return $this;
}
/**
* Get data mapper.
*
* Lazy loads Application_Model_PostMapper instance if no mapper
* registered.
*
* #return Application_Model_PostMapper
*/
public function getMapper()
{
if (null === $this->_mapper) {
$this->setMapper(new Application_Model_PostMapper());
}
return $this->_mapper;
}
/**
* Save the current post.
*
* #return void
*/
public function save()
{
$this->getMapper()->save($this);
}
public function getPost($id)
{
return $this->getMapper()->getPost($id);
}
/**
* Update the current post.
*
* #return void
*/
public function update($data, $where)
{
$this->getMapper()->update($data, $where);
}
/**
* Find a post.
*
* Resets entry state if matching id found.
*
* #param int $id
* #return Application_Model_Post
*/
public function find($id)
{
$this->getMapper()->find($id, $this);
return $this;
}
/**
* Fetch all posts.
*
* #return array
*/
public function fetchAll()
{
return $this->getMapper()->fetchAll();
}
}
getMapper refers to the class Application_Model_PostMapper.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Post');
}
return $this->_dbTable;
}
}
Class of Application_Model_DbTable_Post
class Application_Model_DbTable_Post extends Zend_Db_Table_Abstract
{
protected $_name = 'posts';
}
Let me know if anything is incorrect. i am a newbie to zend and did thsi while referring the zend site. http://framework.zend.com/manual/1.12/en/learning.quickstart.create-model.html
you can extend your script like this. zend dbtable triggers the Zend_Db_Exception on any error during any insert or update.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
try {
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
} catch (Zend_Db_Exception $e) {
// error thrown by dbtable class
return $e->getMessage();
}
// no error
return true;
}
}
now you can check like this
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$isSaved = $post->save();
if ($isSaved === true) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
// error
// $isSaved holds the error message
$this->_helper->flashMessenger->addMessage('Post cannot update');
}