When I'm trying to select custom attributes from record
$data = Emotion::find()
->select('em_id, em_name, tbl_post.post_id, tbl_post.post_header')
->where(['em_id' => $id])
->joinWith('posts')
->one();
I've got an answer model, where related field have full set of table fields.
Trace message looks like this:
app\models\Emotion#1
( [yii\db\BaseActiveRecord:_attributes] =>
[ 'em_id' => 4
'em_name' => 'test_em']
[yii\db\BaseActiveRecord:_related] =>
[ 'posts' =>
[ 0 => app\models\Post#2 ( [yii\db\BaseActiveRecord:_attributes] =>
[ 'post_id' => 10
'post_header' => 'some header'
'post_date' => '2015-06-24 13:40:25',
'post_descr' => 'Rocco, continue the joke'
'post_content' => 'test content'...
So, maybe i did something wrong or this is a framework issue.
Found a workaround here: Yii2 GitHub issue
Which for my case looks like this:
$data = Emotion::find()
->select('em_id, em_name, tbl_post.post_id, tbl_post.post_header')
->where(['em_id' => $id])
->joinWith('posts')
->createCommand()
->queryAll();
And the output of this request will be an raw array.
Is there an another way to have an ActiveRecord object in a response data?
You should simply modify the relation query, e.g. :
$data = Emotion::find()
->select('em_id, em_name')
->where(['em_id' => $id])
->with([
'posts' => function($query) {
$query->select('post_id, post_header');
}
])->one();
And you don't need joinWith since you don't use posts in the main query.
Related
I'm using Cake's $table->find('list') finder method to retrieve an array of associated users [id => name]. Have used it in the past and its worked well. In this find I'm containing a belongsToMany table and retrieving [id => name].
In \App\Model\Table\SitesTable::initialize the ClientUsersWithAuthorities belongsToMany relationship is defined
$this->belongsToMany('ClientUsersWithAuthorities', [
'className' => 'AppUsers',
'joinTable' => 'sites_client_users',
'foreignKey' => 'site_id',
'targetForeignKey' => 'user_id',
'propertyName' => 'client_users_with_authorities']);
In \App\Controller\ClientGroupsController::getClientgroupUsers
$siteClientUsers = $this->Sites->find('list', [
'keyField' => 'client_users_with_authorities.id',
'valueField' => 'client_users_with_authorities.full_name'])
->where(['id' => $siteId])
->contain(['ClientUsersWithAuthorities'])
->toArray();
$siteClientUsers returns [0 => null] instead of [1234 => 'Client 1 name', 5678 => 'Client 2 name'] as expected. Both users exist in the join table.
Three other methods (below) return the array I'm looking for and which I'm expecting $this->Sites->find('list') to produce.
The cookbook describes associated data can be listed.
https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#finding-key-value-pairs
So why isn't $this->Sites->find('list') producing the expected array?
mapReduce
$mapper = function ($data, $key, $mapReduce) {
if (!empty($data['client_users_with_authorities'])) {
foreach ($data['client_users_with_authorities'] as $user) {
$mapReduce->emit($user);
}}};
$siteClientUsers = $this->Sites->find('list', [
'keyField' => 'id',
'valueField' => 'full_name'])
->where(['id' => $siteId])
->contain(['ClientUsersWithAuthorities'])
->mapReduce($mapper)
->toArray();
Hash::combine
$siteClientUsers = $this->Sites->find('all')
->where(['id' => $siteId])
->contain(['ClientUsersWithAuthorities'])
->toArray();
$siteClientUsers = Hash::combine($siteClientUsers,'{n}.client_users_with_authorities.{n}.id', '{n}.client_users_with_authorities.{n}.full_name');
Temp belongsTo relationship on the join table
$table = $this->getTableLocator()->get('SitesClientUsers');
$table->belongsTo('Users', [
'className' => 'AppUsers',
'foreign_key' => 'user_id']);
$siteClientUsers = $table->find('list', [
'keyField' => 'Users.id',
'valueField' => 'Users.full_name'
])
->select(['Users.id', 'Users.full_name'])
->where(['SitesClientUsers.site_id' => $siteId])
->contain(['Users'])
->toArray();
The Cookbook says:
You can also create list data from associations that can be reached with joins
The important part being "that can be reached with joins", which isn't the case for belongsToMany associations. Given that list transformation happens on PHP level, the description should maybe focus on that instead, but it's still kinda valid as it stands.
client_users_with_authorities will be an array, ie possibly multiple records, so you cannot use it to populate a parent record - one Sites record represents one list entry. If you want to find a list of ClientUsersWithAuthorities that belongs to a specific site, then you can either use one of your other solutions (or something similar to that), or you could for example query from the other side of the association and use a matcher on Sites:
$query = $this->Sites->ClientUsersWithAuthorities
->find('list', [
'keyField' => 'id',
'valueField' => 'full_name'
])
->matching('Sites', function (\Cake\ORM\Query $query) use ($siteId) {
return $query->where([
'Sites.id' => $siteId
]);
})
->group('ClientUsersWithAuthorities.id');
This would create joins based on Sites.id, so that you'd only retrieve the ClientUsersWithAuthorities that are associated with Sites where Sites.id matches $siteId.
See also
Cookbook > Database Access & ORM > Query Builder > Filtering by Associated Data
I've got something like this
$query = Customer::find()
->select(['customer.name', 'surname', 'cityName' => 'cities.name', 'streetName' => 'streets.name'])
->joinWith(['city', 'street'])
->where(['group_id' => $id]);
When i do
return $query->all();
it returns only columns from customer table, but when i do something like this
$raw = $query->createCommand()->getRawSql();
return \Yii::$app->user_db->createCommand($raw)->queryAll();
it returns me all 4 columns. Why orm fails?
I'm using custom db connection (user), dynamicly connected after authorization. Anyway ActiveRecord->getDb() has been customized too and it works well till now.
it returns only columns from customer table, but when i do something like this.
Yes, that's right. Because Yii2 AR(Active Record) is ORM pattern. And it's try to return all result off query like object.
So, I will not tell the theory, I'd better suggest a solution variant:
$query = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->asArray()
->all();
return $query;
It's from Yii2 docs(performance tuning).
The result will be like:
[
all data selected from "customer",
['city' => all data selected from city joinWith],
['street' => all data selected from street joinWith]
]
I think, this is exactly what you need.
But, if you need objects. You can try marge objects to only one array.
$customer = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->all();
return [
'customer' => $customer,
'city' => $customer->city,
'street' => $customer->street,
];
you are using
->select(['customer.name', 'surname', 'cityName' => 'cities.name', 'streetName' => 'streets.name'])
so you will get selected columns only.
use,
$query = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->all();
this will give you all the columns
WHen i try to do :
$fields = array('id' => 'custom_id', 'title' => 'some_name');
The result I get has id as a string.
If I do:
$fields = array('custom_id', 'title' => 'some_name');
then it gives custom_id as integer.
How can I obtain custom_id as id without loosing the data type. I read the documentation but didn't found much help.
There is something that virtual fields can do I think. But is it possible inside the find query without the use of virtual fields etc?
Thanks in Advance
As of CakePHP 3.2
you can use Query::selectTypeMap() to add further types, which are only going to be used for casting the selected fields when data is being retrieved.
$query = $table
->find()
->select(['alias' => 'actual_field', /* ... */]);
$query
->selectTypeMap()
->addDefaults([
'alias' => 'integer'
]);
You can use any of the built-in data types, as well as custom ones. In this case the alias field will now be casted as an integer.
See also
API > \Cake\Database\Query::selectTypeMap()
Cookbook > Database Access & ORM > Database Basics > Data Types
Cookbook > Database Access & ORM > Database Basics > Adding Custom Types
With CakePHP 3.1 and earlier
you'll have to use Query::typeMap(), which will not only affect the selected field when data is being retrieved, but in various other places too where data needs to be casted according to the field types, which might cause unwanted collisions, so use this with care.
$query
->typeMap()
->addDefaults([
'alias' => 'integer'
]);
See also
API > \Cake\Database\Query::typeMap()
Change the type of existing columns
Changing the type of an existing column of a table is possible too, however they need to be set using a specific syntax, ie in the column alias format used by CakePHP, that is, the table alias and the column name seprated by __, eg, for a table with the Articles alias and a column named id, it would be Articles__id.
This can be either set manually, or better yet retrieved via Query::aliasField(), like:
// $field will look like ['Alias__id' => 'Alias.id']
$field = $query->aliasField('id', $table->alias());
$query
->selectTypeMap()
->addDefaults([
key($field) => 'string'
]);
This would change the the default type of the id column to string.
See also
API > \Cake\Datasource\QueryInterface::aliasField()
Hi my alternative example full, user schema() in controller Users add type column aliasFiels by join data:
$this->Users->schema()
->addColumn('is_licensed', [
'type' => 'boolean',
])
->addColumn('total_of_licenses', [
'type' => 'integer',
]);
$fields = [
'Users.id',
'Users.username',
'Users.first_name',
'Users.last_name',
'Users.active',
'Users__is_licensed' => 'if(count(LicenseesUsers.id)>=1,true,false)',
'Users__total_of_licenses' => 'count(LicenseesUsers.id)',
'Users.created',
'Users.modified',
'Languages.id',
'Languages.name',
'Countries.id',
'Countries.name',
'UserRoles.id',
'UserRoles.name',
];
$where = [
'contain' => ['UserRoles', 'Countries', 'Languages'],
'fields' => $fields,
'join' => [
'LicenseesUsers' => [
'table' => 'licensees_users',
'type' => 'LEFT',
'conditions' => [
'Users.id = LicenseesUsers.users_id'
],
],
],
'group' => 'Users.id'
];
// Set pagination
$this->paginate = $where;
// Get data in array
$users = $this->paginate($this->Users)->toArray();
i have a ParentItem model
$parentItem = ParentItem::get()->first();
I have this array
$items = array(
array(
'title' => 'test1',
'desc' => 'test1'
),
array(
'title' => 'test2',
'desc' => 'test2'
)
);
i want to add it as a has many relationship.
so i can do:
foreach($items as $item) {
$parentItem->items()->create($item)
}
is there any way way to create all at once..?
something like:
$parentItem->items()->createMany($items);
You can tryout two path.
Using saveMany method:
$parentItem = ParentItem::first();
$items = array(
new Item(['title' => 'test1','desc' => 'test1']),
new Item(['title' => 'test2','desc' => 'test2'])
);
$parentItem->items()->saveMany($items)
For further info you can read here.
https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models
Using insert method:
$parentItem = ParentItem::first();
$items = array(
array('title' => 'test1','desc' => 'test1','parent_item_id' => $parentItem->id),
array('title' => 'test2','desc' => 'test2','parent_item_id' => $parentItem->id)
);
Item::insert($items);
Remember in insert created_at and updated_at won't be inserted automatically, you have to provide them in the array if you have them in your table. For further info you can read here.
https://laravel.com/docs/5.1/queries#inserts
As of right now, you may use the createMany Eloquent method to achieve this.
Details here: https://laravel.com/docs/9.x/eloquent-relationships#the-create-method
I'm using 2 tables with 1 to many relation: campaign and group
This code returns only the relevant campaigns in the group.
$models = Campaigns::model()->with(array(
'Campgroupassoc' => array('condition' => "groupid=$id"),
))->findAll();
while this code:
$dataProvider = new CActiveDataProvider('Campaigns', array(
'criteria' => array(
'with' => array(
'Campgroupassoc' => array(
'condition' => "groupid=$id"
)
),
)
));
returns campaigns which are not in the same group..
What am i doing wrong?
Thx
'Campgroupassoc' => array(
'condition' => "groupid=:id",
'params'=>array(':id'=>$id)
)
Also it is better to specify to what model the groupid belongs to. And of course you can see what SQL dataprovider is generating and analize it.
Edit-----
After consulting with the Yii live chat, i found that even when using eager loading it will result in 2 queries instead of 1...
in order to solve this you need to add:
'together' => TRUE