Cake3 Paginator Sort Error - sorting

I have a very simply model which I want to paginate. The pagination works but the sort links do not have any effect:
My Controller:
public $paginate = [
'limit' => 10,
'order' => [
'Properties.id' => 'asc'
],
'sortWhitelist' => [
'Properties.id',
'Properties.name',
'Properties.active'
],
];
My query:
$properties = $this->Properties->find('all')->where($options)->contain($contains)->order(['Properties.id']);
$this->set('properties', $this->paginate($properties));
My view displays 10 items per page and the links to pages/next/previous work fine. When I click the sort link:
$this->Paginator->sort('id', 'ID')
The url called is:
properties/index/3?sort=id&direction=desc
The page re-loads but the order of the data does not change.

The whitelist expects the exact field name that you are using in sort. It will not automatically prepend the primary table's name, so your whitelist should look like this:
public $paginate = [
'limit' => 10,
'order' => [
'Properties.id' => 'asc'
],
'sortWhitelist' => [
'id',
'name',
'active'
],
];
It will see "id" in the query and check that the exact field name "id" exists in the whitelist.
Also, it appears you are including an order() on your query. To allow the paginator to set the order, you should remove this clause.

Related

jenssegers laravel-mongodb duplicating records on pagination using skip, take and limit

I have been using https://github.com/jenssegers/laravel-mongodb package for interacting with MongoDB. Whenever I fetch a document without skip(), take() and orderBy(), I do not get any duplicate entries. However when I apply skip(), take() and orderBy() to the document, there are duplicate entries on different pages e.g. page 1 have an object with ID 123 and page 2 also have the same object with ID 123.
Please note that there are no duplicates in Mongo DB.
Here is how I am trying to do this:
$record = Model::where('filter1', $algorithm) ->where('filter2', '>=', $asofdate) ->where('filter2', '<', $nextDay);
$record->project(['_id' => 0])->skip($skip)->take($pageSize)->orderBy('column1', 'desc')->get(['column1','column2']);
I also tried using the raw query provided by the package but the issue is still same.
$record = Tree::raw(function($collection) use ($asofdate, $nextDay) {
return $collection->find( [
"$and" => [
["filter1" => "blind_popularity"],
["filter2" => ["$gte" => $asofdate]],
["filter2" => ["$lt" => $nextDay]],
["filter1" => ["$in" => [22]]] ]
],
[ "column1" => 1, "column2"=>1, "column3"=>1, "column4"=>1,
"column5"=>1, "_id"=>0 ],
[ "skip" => 0, "limit" => 15, "sort" => ["column1"=>1]
]);
});
Anybody have interaction with problem like this ?, share your thoughts to solve it.

Laravel Elasticsearch JSON Mapping Issue

I'm currently using Laravel v7.2, have the babenkoivan/scout-elasticsearch-driver installed (4.2) and am using AWS Elasticsearch 7.1. I have several tables mapped in my application that are working fine but am having issues with a nested mapping that was previously working and is now broken.
I'm saving data into a table and having that table data copied into AWS Elasticsearch. I'm using MySQL 5.6 so I am using a TEXT column to store JSON data. Data in the table looks as follows:
'id' => 1,
'results' => [{"finish":1,"other_id":1,"other_data":1}]
I have my model setup with the following mapping:
protected $mapping = [
'properties' => [
'results' => [
'type' => 'nested',
'properties' => [
'finish' => [
'type' => 'integer'
],
'other_id' => [
'type' => 'integer'
],
'other_data' => [
'type' => 'integer'
]
]
],
]
];
And if it's of any use, the toSearchableArray:
public function toSearchableArray()
{
$array = [
'id' => $this->id,
'results' => $this->results
];
return $array;
}
I have no problem creating this index and it worked up until about a couple of months ago. I don't know exactly when, as it wasn't a high priority item and may have occurred around an AWS ES update but not sure why this in particular would break. I receive the following error now:
{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"object mapping for [results] tried to parse field [results] as object, but found a concrete value"}],"type":"mapper_parsing_exception","reason":"object mapping for [results] tried to parse field [results] as object, but found a concrete value"},"status":400}
I've tried also storing the data in the table as such, thinking it was breaking due to the potential array, but it was to no avail:
'id' => 1,
'results' => {"finish":1,"other_id":1,"other_data":1}
I'm at a loss for what else to try to get this working again.
EDIT: Here is the entire model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use ScoutElastic\Searchable;
class ResultsModel extends Model
{
use Searchable;
protected $indexConfigurator = \App\MyIndexConfiguratorResults::class;
protected $searchRules = [
//
];
protected $mapping = [
'properties' => [
'results' => [
'type' => 'nested',
'properties' => [
'finish' => [
'type' => 'integer'
],
'other_id' => [
'type' => 'integer'
],
'other_data' => [
'type' => 'integer'
]
]
],
]
];
public function searchableAs()
{
return 'results_index';
}
public function toSearchableArray()
{
$array = [
'id' => $this->id,
'results' => $this->results
];
return $array;
}
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'results_table';
}
Here is the \App\MyIndexConfiguratorResults::class
<?php
namespace App;
use ScoutElastic\IndexConfigurator;
use ScoutElastic\Migratable;
class MyIndexConfiguratorResults extends IndexConfigurator
{
use Migratable;
protected $name = "results_index";
/**
* #var array
*/
protected $settings = [
//
];
}
This is all that is needed to have Laravel automatically update AWS ES each time the table is updated. For the initial load, I would SSH in and run the following command to have it create the index. This, as well as elastic:migrate and any update/insert into the table produces the mapping error.
php artisan elastic:create-index results_index
Finally figured this out so will share the solution for anyone that runs into this. Turns out to be a fairly simple fix, though I'm not sure how it even worked in the first place so that part is still baffling.
I created a brand new index and update the mappings accordingly to add "id" and remove the type "nested" from the "results" piece. (Adding the "nested" type was adding two "results" to the index - one that contained all my nested data, the other just being "object".)
protected $mapping = [
'properties' => [
'id' => [
'type' => 'integer'
],
'results' => [
'properties' => [
'finish' => [
'type' => 'integer'
],
'other_id' => [
'type' => 'integer'
],
'other_data' => [
'type' => 'integer'
]
]
],
]
];
Then I simply added json_decode to the toSearchableArray() function as so:
public function toSearchableArray()
{
$array = [
'id' => $this->id,
'results' => json_decode($this->results, true)
];
return $array;
}
Voila. It successfully created the index and imported the data in a manner with which I can query the nested object.
Reading through the docs, the type field seems to have been removed. Scroll down to 7.x to see. Also, it seems you need to delete the index and re-add it in order for the new map to work according to this page.

YII2: custom sorting in search model

Please, help me with such a problem:
1) I have default search model of Users.
2) I need a list of users. And first in this list always must be user with login 'admin', and second - with login 'finance', and then all others sorted by id.
My method in UserController
public function actionUsersList() {
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderPartial('users-list', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
As I understood I have to change params of search in this line, to add sort conditions
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
But how exactly can I do this?
You can do that by adding following code to your action:
$dataProvider->sort->attributes['id'] = [
'asc' => [
new \yii\db\Expression("FIELD(login, 'finance', 'admin') DESC"),
'id' => SORT_ASC,
],
'desc' => [
new \yii\db\Expression("FIELD(login, 'finance', 'admin') DESC"),
'id' => SORT_DESC,
],
'label' => $searchModel->getAttributeLabel('id'),
];
$dataProvider->sort->defaultOrder = ['id' => SORT_ASC];
The field function returns the position of first parameter among other parameters or 0 if the value is not present among them. So for 'admin' it will return 2, for 'finance' 1 and for others 0. If you order DESC by that you will get the required order.
Other option is to add this definitions for sort into the search method of UserSearch model as suggested in mahsaa's answer. It depenends if you want to use this sorting in different actions.
In UserSearch class, add sort to ActiveDataProvider:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'login' => SORT_ASC,
'id' => SORT_DESC,
],
]]);
It first sorts by login and then id.

Override eloquent relationship result data

I use Laravel-Metable package in my project. This package return collection object using in key meta name and on value eloquent object.
Here you can see package data result screenshot.
How I can override result data and get this type of array data:
$meta = [
[
'id' => 1,
'key' => "Meta Name",
'value' => "Meta Value"
],
[
'id' => 2,
'key' => "Meta Name",
'value' => "Meta Value"
],
];
I will load my models meta with lazy loading:
use Metable;
protected $with = ['meta'];
You can use the collection map method for that so it should be something like this:
$result = $metaItems->map(function($meta) {
return [
'id' => $meta->id,
'key' => $meta->key,
'value' => $meta->value
];
})->values();
// then $result->toArray(); should give you the expected result

How to add multi select value in database in October CMS Backend?

Not inserted multi select value in database.
My fields.yaml Code is :
related_recipe:
label: 'Related Recipe'
span: auto
nameFrom: recipe_title
descriptionFrom: description
attributes: {multiple:'multiple'}
type: relation
My model code is :
public $belongsTo = [
'related_recipe' => [
'Qdata\Taeq\Models\Recipe',
'conditions' => 'status = 1'
],
];
Currently only one selected value inserted in database.need add multiple value in database. Can any one have the solution of it ?
You should use a $belongsToMany relation in this case.
$belongsTo means your model is link with a single entity of your Recipe model.
To do so with relation you need to go with "belongsToMany" relation. for example:
In your Model
'related_recipes' => [
'Qdata\Taeq\Models\Recipe',
'table' => 'pivot_table_name',
'key' => 'foreign_key_of_pivot_table',
'otherKey' => 'other_key',
],
In related another Model
'makers' => [
'Qdata\Taeq\Models\AnotherModel',
'table' => 'pivot_table_name',
'key' => 'foreign_key_of_pivot_table',
'otherKey' => 'other_key',
],
this will save your multiselect dropdown data in the related pivot table in your database.

Resources