I currently have 2 classes:
workerListClass
workerClass
The workerListClass gets a list of work with ids from database. For each of these the workerClass is called
foreach ($query as $value) {
$result = $this->worker->getWorkerById($value['ID']); // DB Call to get additional data
$this->addData($result);
vardumper::dump($result->getId());
// This results in 1031 and 1528
}
addDate is very simple
public function addData(workerClass $worker): void
{
$this->data[] = $worker;
}
But if i try to go through this array something strange happens
$result = $this->workerListClass->getWorker()->getData();
foreach ($result as $worker) {
vardumper::dump([
$worker->getId() // this outputs 1528 twice!!!
]);
}
getData does nothing special
public function getData(): array
{
return $this->data;
}
Can someone help me why this outputs 1528 twice?
Problem found. The issues was that the same class was changed and not a new class was setup.
Using clone on the workerlist helped fixing this:
foreach ($query as $value) {
$localWorker = clone $this->worker; //starts a new instance so that it is not referenced
$result = $localWorker->getWorkerById($value['ID']);
$this->addData($result);
vardumper::dump($result->getId());
}
Related
I'm Trying to create single array that contains all the ID of parent and child from the database.
But all I was getting is single data.
My ideal output is:
array('160', '161', '162', '163', '164');
what am I getting is only
array('160');
Here is what I've done so far.
public function arrayId(array $elements) {
$where_in = array();
foreach($elements as $element){
if($element->isArray) {
$elems = $this->my_model->select_where('tbl_policies', array('parent_id' => $element->id));
$this->arrayId($elems);
}
$where_in[] = $element->id;
}
return $where_in;
}
$id = 160; //for instance
$elements = $this->my_model->select_where('tbl_policies', array('id' => $id));
$where_in = $this->arrayId($elements);
die(print_r($where_in));
and the data I'm fetching here:
tbl_policies
It's kinda difficult for me to construct questions. So please if something is not clear, do comment below, I'll try my best to make it more understandable. Thanks in advance.
I understand, that you want to delete a parent with all its children and grandchildren. But you do it not directly and sequentially rather want to collect all ids of the records to be deleted. You should go following steps:
Parent-Id (example 160) is already known. Add this to your list.
Write a recursive function such as getChildrenIds(parentId).
Within this function you should iterate over children. And if a child has the flag "isArray" (according to your application logic) then you should call getChildrenIds(currentChildId)
I have written following function. It should work.
public function getChildrenIds( int $parentId, array &$idList) {
$idList[] = $parentId;
$records = $this->my_model->select_where('tbl_policies', array('parent_id' => $parentId));
foreach($records as $r){
if($r->isArray)
$this->getChildrenIds($r->id, $idList);
else
$idList[] = $r->id;
}
return;
}
public function CollectIds(){
$id = 160; //for instance
$where_in = array();
$this->getChildrenIds($id, $where_in);
}
Please notice, that $where_in passed by reference to the recursive function getChildrenIds() and filled there.
I try to retrieve for each region the number of cities with current events.
So I started doing this:
$regionCities = [];
foreach ($regions as $region) {
$regionCities[$region->getId()] = $cityRepository->getCitiesByRegion($region);
}
dump($regionCities);
$regionCitiesNumber = [];
foreach ($regionCities as $index => $region) {
foreach ($region as $city) {
$regionCitiesNumber[$index] = count($city->getCurrentEvents());
}
}
My dump returns me this:
dump
The problem is, it crashes my script, and I suddenly get a blank page when I dump regionCitiesNumber.
getCurrentEvents is a method of my City entity that will retrieve all current events.
public static function createCurrentEventsCriteria(): Criteria
{
return Criteria::create()
->where(Criteria::expr()->gte('endDate', new DateTime('00:00:00')))
->orderBy(['id' => 'DESC'])
;
}
public function getCurrentEvents(): Collection
{
$criteria = EventRepository::createCurrentEventsCriteria();
return $this->events->matching($criteria);
}
Use error logs or try using "Try Catch" wrapper
$regionCities = [];
foreach ($regions as $region) {
$regionCities[$region->getId()] = $cityRepository->getCitiesByRegion($region);
}
//dump($regionCities);
try {
$regionCitiesNumber = [];
foreach ($regionCities as $index => $region) {
foreach ($region as $city) {
$regionCitiesNumber[$index] = count($city->getCurrentEvents());
}
}
} catch (\Throwable $t) {
dd($t);
}
So I tried:
return $this->events->matching($criteria)->count();
And I dumped on regionCitiesNumber, it gave me a totally wrong result:
For example for the ARA region, I end up with 0 as a result while there are 1895 events distributed over all the departments ...
As a result, most regions result in 0, sometimes 1, sometimes 2 ...
In addition, it takes a long time to load my page, isn't there a softer solution?
I'm trying to make a simple template system because I don't want to use Smarty or anything like that.
My current problem is that I can't make 1 tag print every result from a while loop. It only prints the first result.
public $TplKey = array();
public function GetContent($file, $data) {
$template = file_get_contents($file);
foreach($data as $key => $value) {
$template = str_replace('{'.$key.'}', $value, $template);
}
return $template;
}
public function View($file) {
return $this->GetContent($file, $this->TplKey);
}
public function TplKeyAdd($key, $value) {
return $this->TplKey += array($key => $value);
}
public function testing() {
global $DBHandle;
$q = $DBHandle->mysqli->query("SELECT * FROM site_users");
while($qf = $q->fetch_array()) {
$r = $this->TplKeyAdd("var", $qf["user_name"]);
}
return $r;
}
Then, later on in my .TPL file I call {var}. But it only shows the first database row (as stated). I want it to show every row it can find. How can I solve this?
Your issue lies with how you're storing the key => value pairs in the TplKeyAdd method.
I believe you're after:
public function TplKeyAdd($key, $value) {
return $this->TplKey[] = array($key => $value);
}
Also with this:
$this->TplKeyAdd("var", $qf["user_name"]);
The key you're adding every time is called "var" so each value from the database doesn't have it's own key.
Edit: Also as ianinn pointed out, you shouldn't be returning within your while look as it'll only get the first iteration.
I have a static method 'findAll' on a model which basically gets all rows with certain criteria. This method works fine and I can call it using:
$m::findAll();
Where $m is the model name as a variable. I can output this and it returns correct results. However, when assigning this to a variable in the Zend_View object, as:
$this->view->viewvariable = $m::findAll();
I get the error:
Zend_Db_Table_Exception: Too many
columns for the primary key
Any ideas why?
Find all function:
final public static function findAll($where = false, array $options = array()) {
$object = new static();
if (!empty($options)) $options = array_merge($object->options, $options);
else $options = $object->options;
$run = $object->buildDefaultSelect($where, $options);
$rows = $run->fetchAll();
if ($options['asObject'] == true) {
$result = array();
foreach ($rows as $r) {
$class = new static();
$class->setInfo($r);
$result[] = $class;
}
return $result;
} else {
if (count($rows) > 0) return $rows;
else return array();
}
}
Note: This function works fine everywhere apart from when assigning to a view variable. If I run the below (not assigning it to a view variable), it shows the correct array data.
var_dump($m::findAll($module['where'], $module['options']));
exit;
In my view (I have replaced the actual name with viewvariable for the sake of this post):
<?php foreach($this->viewvariable as $item) { ?>
//Do some echoing of data in $item
//Close foreach
I doubt the issue is with Zend_View. It's hard to tell without seeing your code, but my guess is that findAll() is using the Zend_Table_Db find() function incorrectly.
To my knowledge, the only place that throws that exception is the find() function on Zend_Db_Table_Abstract.
Perhaps, inside the findAll() function (or in a function it calls) you're doing one of these:
$zendDbTable->find(1,2) //is looking for a compound key
$zendDbTable->find(array(1,2)) //is looking for two rows
When you really want the opposite.
I want to copy a record with all his relations.
I'm trying with:
$o = Doctrine::getTable('Table')->Find(x);
$copy = $object->copy();
$relations = $o->getRelations();
foreach ($relations as $name => $relation) {
$copy->$relation = $object->$relation->copy();
}
$copy->save();
This code doesn't works, but I think it's on the way.
I never could get the deep copy function to operate correctly.
I manually coded a deep copy function for one of my models like this
public function copyAndSave ()
{
$filters = array('id', 'created');
$survey = $this->copy();
$survey->Survey_Entries = new Doctrine_Collection("Survey_Model_Entry");
$survey->Assignment_Assignments = new Doctrine_Collection("Assignment_Model_Assignment");
$survey->Survey_Questions = new Doctrine_Collection("Survey_Model_Question");
$survey->save();
foreach ($this->Survey_Questions as $question)
{
$answers = $question->Survey_Answers;
$newQuestion = $question->copy();
$newQuestion->survey_surveys_id = $survey->id;
$newQuestion->save();
$newAnswers = new Doctrine_Collection("Survey_Model_Answer");
foreach($answers as $answer)
{
$answer = $answer->copy();
$answer->save();
$answer->survey_questions_id = $newQuestion->id;
$newAnswers->add($answer);
}
$newQuestion->Survey_Answers = $newAnswers;
$survey->Survey_Questions->add($newQuestion);
}
return $survey->save();
}
You can read about copy() here. It takes an optional parameter $deep:
$deep
whether to duplicates the objects targeted by the relations
So
$copy = $object->copy(true);
should do it.
Sorry if I'm resurrecting this thread...
I found myself in search of a solution recently where I needed to copy a record and retain the references of the original. A deep copy $record->copy(true) copies the references, which was no good for me. This was my solution:
$record = Doctrine_Core::getTable('Foo')->find(1);
$copy = $record->copy();
foreach($record->getTable()->getRelations() as $relation) {
if ($relation instanceof Doctrine_Relation_Association) {
$ids = array();
foreach ($relation->fetchRelatedFor($record) as $r) {
$ids[] = $r->getId();
}
$copy->link($relation->getAlias(), $ids);
}
}
if ($copy->isValid()) {
$copy->save();
}
Hope this helps :)
This is how i done, but some fix is needed.
$table = $entidade->getTable();
$relations = $table->getRelations();
foreach($relations as $relation => $data) {
try {
$entity->loadReference($relation);
} catch(Exception $e) {
die($e->getMessage());
}
}
I am using Symfony1.4.1 and that uses Doctrine 1.2.1 (I think).
I have been trying to make a function that did all the above myself, when I found one that already exists.
Try this in any function and look at the results:
$tmp=$this->toArray(TRUE);
var_dump($tmp);
$this->refreshRelated();
$tmp=$this->toArray();
var_dump($tmp);
$tmp=$this->toArray(TRUE);
var_dump($tmp);
exit();
I am going to try two different things:
A/ put $this->refreshRelated() into the constructor of all my model objects.
B/ write a function that takes an array depicting the object graph that I want populated. Calling the function refereshRelatedGraph($objectGraphArray). With the right structure of the array (having all the appropriate relation names at each level), I could control which relations get populated and which don't. One use for this is to populate only children, not parent relations. The other is for when a ERD/Schema/ObjectGraph has an element that is 'owned' by more than one object (many to many, other special circumstances that I have), I could control which side of the relationships get pre(non lazy) loaded.