Yii2 - decimal less than 1 without leading 0 - php

Basically in my MSSQL DB the record has column of value 0.21, however in the view (model read from DB) it is .21 everywhere without leading 0. Is it possible to change this behavior?

I'm not a MSSQL expert, but in this case .21 is probably returned as a string by PDO. String .21 will be recognized as a number, so 1 + '.21' will return 1.21, but when you want to just display this string, no transformation will be done. The easiest way (at least from PHP side) would be to typecast this value to float:
echo (float) '.21'; // 0.21
You can also configure AttributeTypecastBehavior to do this automatically at active record level:
public function behaviors() {
return [
'typecast' => [
'class' => AttributeTypecastBehavior::class,
'attributeTypes' => [
'my_attribute' => AttributeTypecastBehavior::TYPE_FLOAT,
],
],
];
}

Related

How to generate mobile phone number with Faker

I'm using Laravel 9 and I want to make a faker for my users table:
public function definition()
{
return [
'usr_first_name' => fake()->name(),
'usr_last_name' => fake()->name(),
'usr_user_name' => fake()->unique()->name(),
'usr_mobile_phone' => , // generates a unique phone number
'usr_password_hash' => Hash::make('123456'),
'usr_email_address' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'usr_is_superuser' => now(),
'usr_is_active' => 1,
'usr_str' => Str::random(10),
'remember_token' => Str::random(10),
];
}
So as you can see for the column usr_mobile_phone, I need to add a unique mobile number which has 11th character length.
But I don't know what is the command for doing that in faker!
So if you know, please let me know, thanks in advance.
You can use the fake()->e164PhoneNumber() method to get a phone number (E164 format) with the plus sign and country code, based on the app locale which you can customise.
Now to get unique phone number we can combine the use of unique() method: fake()->unique()
This should get you unique phone number:
fake()->unique()->e164PhoneNumber()
Example output: +14809888523, +12705838722, +13869134701
...now as per your requirement of 11 digit length, you can replace the plus sign:
'usr_mobile_phone' => str_replace('+', '', fake()->unique()->e164PhoneNumber())
Please note that different countries have different country code length, resulting in different phone number length output which you need to take care of yourself.
Alternatively, you can use the fake()->numerify() method to generate dynamic format number by passing the the format to the method or by default format ###:
fake()->unique()->numerfiy('##########');
Example output: 0733375159, 8270962398, 5125950018
...and then join the country code:
'usr_mobile_phone' => '1' . fake()->unique()->numerfiy('##########')

Elasticsearch - Want to sort by field in all indices where that particular field available or not if not then avoid it

Currently, Getting result based on scoring but what i want to do is i want a result based on scoring + Field Status with value true/false.
If value is true then needed that results in priority but there is possibility that status field is not exist in all indices.
"query" => [
'bool' => [
'filter' => $filter,
'must' => [
"multi_match" => [
'query' => "$string",
"type" => "cross_fields",
'fields' => ['field1','field2','field3'],
"minimum_should_match" => "80%"
]
]
]
],
"sort" => [
"_score",
[ "status" => ["order" => "desc","unmapped_type" => "boolean"] ]
],
But getting error below :
[type] => illegal_argument_exception
[reason] => Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [status] in order to load field data by uninverting the inverted index. Note that this can use significant memory.
Anyone help me out to ignore for indices where that field not available or any other solution with this problem?
As discussed in the chat, the issue happened due to #jilesh
forget to delete the old index mapping and only upate the data that's what this thing was occurring.
Below answer is relevant when you get below error with proper setup
Text fields are not optimised for operations that require
per-document field data like aggregations and sorting, so these
operations are disabled by default. Please use a keyword field
instead. Alternatively, set fielddata=true on [status] in order to
load field data by uninverting the inverted index. Note that this can
use significant memory.
In that case, please enable the field data on the field if you want to get rid of the error but beware it can cause performance issues.
Read more about the field data on official site.
You can enable it in your order field in your mapping as shown.
{
"properties": {
"order": {
"type": "text",
"fielddata": true
}
}
}
works for me
curl -X PUT -H "Content-Type: application/json" \
-d '{"properties": {"format": { "type":"text","fielddata": true}}}' \
<your_host>:9200/<your_index>/_mapping
In my case, I had to use the aggregatable {fieldname}.keyword field. Here's an example using Nest .NET.
.Sort(s => s
.Ascending(f => f.Field1.Suffix("keyword"))
.Ascending(f => f.Field2.Suffix("keyword"))
.Ascending(f => f.Field3.Suffix("keyword")))

How to add a "pipe" into a get parameter during guzzle query building

I'm using an api that has a "range" parameter that can apply to several different parameter items. The range i'm focusing on is "price". I'm using guzzle in laravel and according to the api documentation, the query for this particular parameter should be written like this "&range_facet=price|500|2500|250"...this is broken down into the minimum, maximum, and interval values of the price range parameter. That's not necessarily important to this question. When i try and run this query as is, i get nothing returned. When I remove that particular parameter, i get values but obviously they're not filtered the way i want them to be. When i run this in Insomnia, the pipes are replaced by "%7C", which is obviously (obviously?) not interpreted by the api as it's not how it's waiting for the GET request to be made. How can I insert the pipes into the query so that it calls the correct way?
I've tried to create an additional nested array with the price value being broken up into key value pairs but that didn't work either.
'range_facets' => ['price'['start'=>'500', end=>'2500', 'interval'=>'250']],
$client = new Client();
$result = $client->request('GET', "http://api.example.com", [
'headers' => [
'Host' => 'example-host',
'Content-Type' => 'application/json'
],
'query' => [
'api_key' => 'my_api_key',
'range_facets' => 'price|500|2500|250',
'year' => $year,
'latitude' => '30.170222',
'longitude' => '92.01320199',
'radius' => 500,
'start' => 0,
'rows' => 50
]
]);
I'd like to filter my prices but I need the pipe to be able to do it.
This is exactly how it should be. %7C should be decoded on the server side to | automatically (about query string encoding).
I bet the issue is in different place.

object to json_encode return false in linux server cakephp 3

I'm facing a horrible problem in Linux server. I don't understand what to do now.
My problem is that in Linux server my script runs properly without any error but when I use an object to JSON encode it returns false.
Please any one help. Thanks in advance.
public function ajaxDataSearch() {
$this->loadModel('ViewDocketHistorys');
$this->render(false);
$this->viewBuilder()->layout('false');
if ($this->request->is(['post'])) {
$DocketNo = $this->request->data['DocketNo'];
$SearchData = $this->ViewDocketHistorys->find()
->where(['DocketNo' => $DocketNo])
->last();
$Jsondate = json_encode($SearchData);
echo $Jsondate;
}
}
When I debug query data
debug($SearchData); exit;
output:
object(App\Model\Entity\ViewDocketHistory) {
'MasterID' => (int) 311,
'DocketNo' => 'fhfghfghf',
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'ViewDocketHistorys'}
When I debug JSON encode
debug($Jsondate); exit;
Output:
false
Last found a solution When I create a view with a UNION, i have to make sure the data types of the corresponding columns are the same (or at least, similar enough for one to be converted to the other). In the current case, the first column of the view is a 'column1', and no data type definition apart from BLOB can make much sense of that.
If you really need this as a view, you could try...
SELECT e.ID AS ID,
NULL AS table_field,
...etc...
'e' AS type
FROM table1 AS e
UNION ALL
SELECT
NULL AS ID,
k.table_field AS table_field,
...etc...
'k' AS type
FROM table2 AS k;
Details here
You can try by doing:
$Jsondate = json_encode($SearchData->toArray());
->toArray() will convert entity class into a clean array, after that, json_decode would receive the right structure to JavaScript Object Notation.

Yii2: Writing to database the date/time of the current record via expression

There is table with some columns. One of it date_of_record. Means the date when current row is inserted in database. In current version i just calculate this field in PHP code before save().
How it should be correctly done via expression? Example by opportunity
Use Timestamp Behaviors In Controller :
use yii\db\Expression;
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'date_of_record',
'value' => new Expression('NOW()'),
],
];
}
References
1) Timestamp Behaviors
2) Concept Behaviors

Categories