Can we add custom values to a CakePHP Table Object? - php

I have a Cake Object when querying a table:
$invoices = TableRegistry::get('invoices')->find('all', ['conditions' => ['order_number =' => $orderNumber]]);
This works fine. I then want to add other array key/values to this Object, like this one:
$invoicesTmp = array();
$invoicesTmp['customer'] = "name of customer";
But $invoicesTmp is incompatible with $invoices. (one is an array, other is an CakePHP Object)
I have tried this:
compact($invoices, $invoicesTmp);
but that didn't worked.

The find() method of a Table object returns a Cake\ORM\Query object. This object is used to build SQL queries and to execute them. It has some features to define how the results from the query should be returned.
When CakePHP fetches results from the database the records are stored as an array, and CakePHP then converts them to Entity objects. A process called "hydration" of entities. If you disable hydration the records are returned as just an array.
$query = TableRegistry::get('invoices')
->find()
->where(['order_number'=>$orderNumber])
->enableHydration(false);
foreach($query as $record) {
pr($record);
}
The above creates a query object, and you can iterate over the query records because the object itself supports iteration.
The query object implements the Cake\Collection\CollectionInterface interface, which means we can perform a bunch of collection methods on it. The most common method is the toArray().
$invoices = TableRegistry::get('invoices')
->find()
->where(['order_number'=>$orderNumber])
->enableHydration(false)
->toArray();
The $invoices variable is now a valid array object holding the all the records with each record as an array object.
You can now easily use array_merge to assign extra metadata to each record.
$invoices = array_map(function($invoice) {
return array_merge(['customer'=>'name of customer'], $invoice);
}, $invoices);
$this-set(compact('invoices'));
Updated:
Based upon the comments it appears you wish to use two different tables with different column names, but those columns represent the same data.
Field Aliases
You can rename fields in the SQL query to share a common alias.
$table = TableRegistry::get($whichTable ? 'table_a' : 'table_b');
$records = $table->find()
->select([
'id',
'invoice_id',
'name' => ? $whichTable ? 'customer_name' : 'invoice_name'
])->all();
The above selects a different column for name depending upon which table is being used. This allows you to always use $record->name in your view no matter which table.
I don't like this approach, because it makes the source code of the view file appear to reference a property of the entity that doesn't really exist. You might get confused when returning to the code later.
Field Mapping
From a MVC perspective. Only the controller knows what a view needs. So it's easier if you express this knowledge as a mapping.
$map = [
'id'=>'id',
'invoice_id'=>'invoice_id',
'name' => ? $whichTable ? 'customer_name' : 'invoice_name'
];
$table = TableRegistry::get($whichTable ? 'table_a' : 'table_b');
$records = $table->find()
->select(array_values($map))
->all();
$this->set(compact('records','map'));
Later in your view to output the columns you do it like this:
foreach($records as $record) {
echo $record->get($map['name']);
}
It becomes verbose as to what is happening, and why. You can see in the view that the controller provided a mapping between something called name and the actual field. You also know that the $map variable was injected by the controller. You now know where to go to change it.

Related

Propel - get primary key after find

The question boils down to finding the proper way how to getPrimaryKey when iterating over a yielded result. When using select method, the result is an object of ArrayCollection which doesn't provide the getPrimaryKey method. A simple snippet
$q = UserQuery::create();
$q->select('a', 'b'); //yields an ArrayCollection object, doesn't have getPrimaryKey method when iterated
$q->find();
However,
$q = UserQuery::create();
$q->find(); //yields an ObjectCollection object, has getPrimaryKey method when iterated
Update
I have tried to use the setFormater to force using the ObjectCollection. Ultimately, it resulted in exception being thrown.
$q = UserQuery::create()
->setFormater(ModelCriteria::FORMAT_OBJECT)
->select('a', 'b')
->find(); //Error populating object
Update 2
Providing an exact use case, since it may be unclear at first what I am looking for. I have a table with >100 columns. I am providing the functionality using behaviour to not disable (not select) some of them. Thus, I am unseting some of the columns, and basing the $q->select on the remaining ones.
if (!empty($tableQuery->tableColumnsDisable)) {
$columns = $tableQuery->getTableMap()->getColumns();
foreach ($columns as $index => $column) {
if (!empty($tableQuery->tableColumnsDisable[$column->getName()])) {
unset($columns[$index]);
continue;
}
$columns[$index] = $column->getName();
}
//TODO - returns array collection, object collection needed
$tableQuery->select($columns);
}
When using select(), Propel will skip object hydration and will just return an ArrayCollection containing an array for each result row.
To retrieve the id of each result row, you need to add the column name to the select(). You can then just retrieve the value from the row arrays by using the column name:
$users = UserQuery::create()
->select(['id', 'a', 'b'])
->orderBy('c')
->find();
foreach ($users as $user) {
$id = $user['id'];
}
The select functionality is described in the documentation and in the docblock of Propel\Runtime\ActiveQuery\ModelCriteria#select() (source).
When you are using Propel 1, the functionality is the same. Read more about it in the Propel 1 documentation or the docblock of ModelCriteria#select() (source).

Symfony2 - Doctrine query

I have problem with Doctrine query in my Symfony2 project.
That my code:
public function getLender($lender) {
$lender = str_replace("_", " ", $lender);
$this->qb->select('ld, ld.entry, ll.name, ll.logo')
->from('PageMainBundle:LoanDescription', 'ld')
->leftJoin(
'PageMainBundle:loanLender',
'll',
\Doctrine\ORM\Query\Expr\Join::WITH,
'ld.lender = ll.lenderId'
)
->where('ll.name=?1')
->setParameter(1, $lender);
return $this->qb->getQuery()->getResult();
}
When in select section i choose columns it works very well - returns values of columns. unforunelly when I try something like that:
$this->qb->select('ld')
I don't get pure values but sometkhing strange.
How can I get values of all db columns?
This "strange" thing is most probably an LoanDescription collection of object (entity) instances. So to get value of entry field you need to call $entity->getEntry() on this entity object (assuming that you have such method defined in your entity)
OR
You can use getArrayResult instead of getResult and you should get array with valies

php Yii Nested json array

First code:
$result=ResPlaces::model()->findall($criteria);
/*foreach($result as $value)
{
$model_name=ResRegistration::model()->findByAttributes(array('id'=>$value->user_id));
$model_image=ResImages::model()->findByAttributes(array('place_id'=>$value->id),array('limit'=>'1'));
}*/
}
echo CJSON::encode($result);
?>
i need to add model_name->company_name & $model_image->image
to my echo json array
Try to load the relations within the findAll so you don't need the foreach.
ResPlaces::model()->with('ResRegistration', 'ResImages')->together()->findAll($criteria);
For ResRegistration and ResImages use the relation names as defined in your model.
If you don't need all fields of these relations, you can specify a select in your $criteria.
See the guide for more info.
edit: I am not quite sure, why you cannot use relation. However you will need a loop, like you already have. Here is how you do it without relations:
First add the fields you want to use to your model. In this case
class ResPlaces extends CActiveRecord
{
public $name; // check that these do not collide with your models db fields
public $image;
[...]
}
In your controller do the loop like you did before:
foreach($result as $key => $value)
{
$result[$key]->name = ResRegistration::model()->findByAttributes(array('id' => $value->user_id));
// findByAttributes returns only one record, so you don't need the limit here
// if you want multiple records, you have to use findAllByAttributes
$result[$key]->image = ResImages::model()->findByAttributes(array('place_id' => $value->id), array('limit' => '1'));
}
That should do it. However I wouldn't recommend this way, because you have lots of additional database requests. If your $result is populated with say 100 records, you have in sum 200 additional queries which are not nessassary with a relation.
Note also that if you need these two other fields more often, it may be better to put these two queries which are now in the controller in your model. The afterFind() would be the right place.

Building Eloquent query with "raw" column in column list

I'm using Eloquent to build a query, passing an array of columns to the get() method to specify the column names that I want returning; but I'd also like to add one calculated column
YEAR(CURDATE())-YEAR(`dateOfBirth`) - (DAYOFYEAR(CURDATE()) < DAYOFYEAR(`dateOfBirth`)) as AGE
I know that I can specify parts of a WHERE or HAVING clause as raw, or the entire query as raw if I create it manually; but I'd rather use Eloquent's fluent interface to build the query.
Is there any way I can define this one column in the SELECT list as raw so that Eloquent doesn't wrap it in backticks?
EDIT
Alternatively, is there any way I can define the model, perhaps with a callback, of creating an age property and calculating the value in PHP when the model is populated?
Alternatively, is there any way I can define the model, perhaps with a callback, of creating an age property and calculating the value in PHP when the model is populated?
You want an accessor in your model.
public function getAgeAttribute() {
// do an age calculation on $this->dateOfBirth here
return $age;
}
Calling $model->age would then spit out the result of the calculation.
After examining the Eloquent code, and noting that (with the exception of *) all entries in the fields array that's passed to the query get() method are wrapped in backticks unless they are Query\Expression objects, the solution that I came up with was:
$joins = [
];
$columnnames = [
'id',
'roleId',
'category'
]
$calculatedFields = [
new Illuminate\Database\Query\Expression(
"YEAR(CURDATE())-YEAR(`dateOfBirth`) - (DAYOFYEAR(CURDATE()) < DAYOFYEAR(`dateOfBirth`)) as age",
),
new Illuminate\Database\Query\Expression(
"CONCAT(`forename`, ' ', `surname`) as fullname",
),
];
$modelName = 'User';
$query = (empty($joins)) ?
(new $modelName)->newQuery() :
(new $modelName)->with($this->joins);
$results = $query
->get(
array_merge(
$columnNames,
$calculatedFields
);
);
Posted here for the benefit of anybody else struggling to find any documentation explaining how to do this.

Symfony2 Doctrine2 how to add object if not fetched from db

Check this example: http://symfony.com/doc/current/book/doctrine.html#fetching-objects-from-the-database
What I got is:
$results = $applicationsRepo->findByInName($appInNames);
Where appInNames is an array looking like this:
array(
app1_name => app1_name,
app2_name => app2_name,
app3_name => app3_name,
...
)
I want to create an entity object when it's not found. How to check if app1_name was returned and if not create one ?
If you need to get an array of all entities that have inName attribute set to either of app1_name, app2_name, etc with a default value if it does not exists, you can use findOneBy instead of findBy and create your entity if the result is NULL.
May not be the most efficient method because of the loop but it give you what you need :
$results = array();
foreach($appInNames as $appInName) {
$app = $applicationsRepo->findOneByInName($appInName);
if(!isset($app)) {
// Create you entity here
}
$results[$appInName] = $app;
}
A more efficient method may be to write a custom Repository and use the queryBuilder to add all your OR conditions. You'll get all the existing entities in one query, you will then have to parse the result to create the missing entities.

Categories