Yii2 update with multiple conditions - yii2

$this->localdb->createCommand()
->update(
$this->MYTable,
[
'name' => $el['new'],
'data' => $el['data'],
],
[
'userId', $this->user,
'product_id', $this->productId,
'name', $el['old'],
'created', $el['date'],
'category', $el['cat'],
]
);
I tried to use the following command to update a row using multiple where conditions, but it doesn't work for some reason. The documentation doesn't seem to cover this case and doesn't seem to be updated, because the update() method seems to match the updateAll method instead of the update method for some reason (maybe it was updated?). So I was wondering what was the correct way to do this.

You have a syntax error. Try following:
$this->localdb->createCommand()
->update(
$this->MYTable,
[
'name' => $el['new'],
'data' => $el['data'],
],
[
'userId' => $this->user,
'product_id' => $this->productId,
'name' => $el['old'],
'created' => $el['date'],
'category' => $el['cat'],
]
);

Try This updateAll query :
MYTable::updateAll([ // field to be updated in first array
'name' => $el['new'],
'data' => $el['data']
],
[ // conditions in second array
'userId' => $this->user,
'product_id' => $this->productId,
'name' => $el['old'],
'created' => $el['date'],
'category' => $el['cat']
]);

Related

Yii2 grid sorting is not correct with ArrayDataProvider

I'm using array data provider for grid view widget since the data source is an API response. It's working fine, but when I try to sort the 'Name' column, it's sorting incorrectly with the lowercase first letters. Please check the table grid screenshot. The API response which I'm receiving is correct with the current sorting.
1. Table Grid
2. Model
$provider = new ArrayDataProvider([
'allModels' => #$response->data,
'pagination' => false,
'sort' => [
'attributes' => ['id', 'name', 'shortDescription'],
],
]);
3. View
<?= GridView::widget([
' dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
'shortDescription'
],
'options' => ['class' => 'content'],
'tableOptions' => ['class' => 'table table-striped table-hover'],
'summary' => Yii::t('app', 'Showing').' {begin}-{end} of '.$total.' '.Yii::t('app', 'items')
]);
?>
Please guide me to fix this. Thanks!

Getting associated data in CakePHP 3.x

I have this setup in my Table classes
Icases table
$this->table('icases');
$this->displayField('name');
$this->primaryKey('id');
$this->belongsTo('Clients', [
'foreignKey' => 'client_id'
]);
$this->hasMany('Documents', [
'foreignKey' => 'icase_id'
]);
$this->belongsToMany('Users', [
'foreignKey' => 'icase_id',
'targetForeignKey' => 'user_id',
'joinTable' => 'icases_users'
]);
Clients Table
$this->table('clients');
$this->displayField('name');
$this->primaryKey('id');
$this->hasMany('Icases', [
'foreignKey' => 'client_id'
]);
$this->belongsToMany('Users', [
'foreignKey' => 'client_id',
'targetForeignKey' => 'user_id',
'joinTable' => 'clients_users'
]);
IcasesUsers Table
$this->table('icases_users');
$this->displayField('icase_id');
$this->primaryKey(['icase_id', 'user_id']);
$this->belongsTo('Icases', [
'foreignKey' => 'icase_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
In Icases table I have this SQL, which retrieves active and pending case data for related client and the user who is logged in. This works fine until user sets filter to include archived cases as well as active and pending which returns 107077 rows and I am getting a memory error.
Is there anyway to write this sql using contain() and get data in chunks before serving it to user, so that it cross the memory limit?
$cases_data = TableRegistry::get('icases')->find('all')
->select(['icases.id', 'icases.state', 'icases.client_id', 'icases.name', 'icases.age', 'clients.name'])
->innerJoin('icases_users', 'icases_users.icase_id = icases.id')
->where($conditions)
->innerJoin('clients', 'clients.id = icases.client_id')
->group(['icases.id'])
->order(['clients.name' => 'ASC', 'icases.name' => 'ASC'])
->execute()
->fetchAll('assoc');
You could paginate your result.
See the Paginator Helper and Pagination Component documentation.

CakePHP 3 CounterCache not updating on delete with belongsToMany SelfJoinTable

CakePHP vertion: 3.3.11
CounterCache working on add method but not working on delete method.
SentenceTable
$this->belongsToMany('Sentences', [
'foreignKey' => 'second_sentence_id',
'targetForeignKey' => 'sentence_id',
'joinTable' => 'sentences_sentences'
]);
$this->belongsToMany('SecondSentences', [
'className' => 'Sentences',
'foreignKey' => 'sentence_id',
'targetForeignKey' => 'second_sentence_id',
'joinTable' => 'sentences_sentences'
]);
SentencesSentencesTable
$this->belongsTo('Sentences', [
'foreignKey' => 'sentence_id',
'joinType' => 'INNER'
]);
$this->belongsTo('SecondSentences', [
'className'=>'Sentences',
'foreignKey' => 'second_sentence_id',
'joinType' => 'INNER'
]);
$this->addBehavior('CounterCache', ['Sentences' => ['ver_count']]);
SentencesController Add method updating ver_count
$sentence = $this->Sentences->get($this->request->data['id']);
$sentence = $this->Sentences->patchEntity($sentence, $this->request->data);
$this->Sentences->SecondSentences->saveStrategy('append');
$this->Sentences->save($sentence);
SentencesController delete method not updating ver_count
$sentence = $this->Sentences->SecondSentences->get($this->request->data['id'],['contain'=>['Sentences']]);
if ($sentence->user_id == $this->Auth->user('id')) {
$this->Sentences->SecondSentences->delete($sentence);
$sentences = $this->Sentences->get($sentence->sentences[0]->id,['contain'=>['SecondSentences']]);
// NOW I AM USING BELOW CODE FOR UPDATING VER_COUNT.
$this->Sentences->updateAll(['ver_count'=>count($sentences->second_sentences)], ['id'=>$sentence->sentences[0]->id]);
}
How are your records deleted. Just as mentioned in cakephp documentation (CounterCache):
The counter will not be updated when you use deleteAll(), or execute SQL you have written.
And:
The CounterCache behavior works for belongsTo associations only.
Just confirm about that first.

how to write mysql AND/OR in cakephp find() method [duplicate]

This question already has answers here:
cakephp OR condition
(4 answers)
Closed 6 years ago.
I wanted to find out a way to write the following code into cakephp find() method but the didn't find related resource on the cakebook.
my code is
SELECT * FROM Customers
WHERE
(Country='Germany' AND City='München')
OR (Country='Germany' AND CustomerName='München');
please share a way to write this accordingly in find() method. Thanks
You can do this using the OR key when using where:
$query = $this->Customers
->find()
->where([
'OR' => [
[
'City' => 'München',
'Country' => 'Germany'
],
[
'Country' => 'Germany',
'CustomerName' => 'München'
]
]
]);
This could be simplified to:
$query = $this->Customers
->find()
->where([
'Country' => 'Germany',
'OR' => [
['City' => 'München'],
['CustomerName' => 'München']
]
]);
See http://book.cakephp.org/3.0/en/orm/query-builder.html#advanced-conditions, I find using the andWhere and orWhere functions in combination so just stick to where!
Try
$query = $this->Customers->find(
'all',
[
'conditions' => [
'Country' => 'Germany',
'OR' => [
[
'City' => 'München',
],
[
'CustomerName' => 'München'
]
]
]
]
);
In the cookbook it says to wrap the or conditions in arrays if they are pertaining to the same field http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#complex-find-conditions
If you want to paginate results you can try this:
public function yourFunctionName() {
$this->paginate['conditions']['and'][] = ['Country' => 'Germany'];
$this->paginate['conditions']['and']['or'][] = ['City' => 'München'];
$this->paginate['conditions']['and']['or'][] = ['CustomerName' => 'München'];
$customers = $this->paginate($this->Customers);
$this->set(compact('customers'));
$this->set('_serialize', ['customers']);
}

How to cache database translations on yii2

How to cache database translations on yii2
I tried the following but not worked
'i18n' => [
'class' => Zelenin\yii\modules\I18n\components\I18N::className(),
'languages' => ['en', 'ar', 'fr'],
'sourceMessageTable' => 'source_message',
'messageTable' => 'message',
'cache' => 'cache'
],
The problem is in Zelenin i18n module. If you look at Module.php file, you can see:
$this->translations['*'] = [
'class' => DbMessageSource::className(),
'sourceMessageTable' => $this->sourceMessageTable,
'messageTable' => $this->messageTable,
'on missingTranslation' => $this->missingTranslationHandler
];
in init() method. This Code set DbMessageSource options and there are no any options about caching. Module have no any caching options too.
If you change this code to:
$this->translations['*'] = [
'class' => DbMessageSource::className(),
'sourceMessageTable' => $this->sourceMessageTable,
'messageTable' => $this->messageTable,
'enableCaching' => true,
'cachingDuration' => 3600,
'on missingTranslation' => $this->missingTranslationHandler
];
Cache will work. Some SELECT messages will gone from debug list.
The Yii documentation for i18n db messages says that the property cache only has meaning when the property cacheDuration is not zero. I suggest you set this value, so;
'i18n' => [
'class' => Zelenin\yii\modules\I18n\components\I18N::className(),
'languages' => ['en', 'ar', 'fr'],
'sourceMessageTable' => 'source_message',
'messageTable' => 'message',
'cache' => 'cache',
'cacheDuration' => 3600
],