I implementing a custom search, and now I need to select values in range for date column.
public function search($params)
{
$query = Books::find();
//.....
$timestampStart = strtotime($this->dateStart),
$timestampEnd = strtotime($this->dateEnd)
// How to add BETWEEN here?!!?!
$query->andBetween('date', $timestampStart, $timestampEnd) // pseudo-code
From the documentation, it's not entirely clear how to use that:
https://github.com/yiisoft/yii2/blob/master/docs/guide/db-query-builder.md
From the docs here, you can use a where method call for this.
between: operand 1 should be the column name, and operand 2 and 3 should be the starting and ending values of the range that the column
is in. For example, ['between', 'id', 1, 10] will generate id BETWEEN
1 AND 10.
So, in your case, it would look something like:
$query->where(['between', 'date', $timestampStart, $timestampEnd]);
For more information on building queries, you can also see this.
Related
I want to generate a unique id in Laravel.
EX: PO-12010001
PO = product,
12 = the month,
01 = the year,
0001 = ID of product.
I have tried googling and the answer is using UUID but could not understand.
Your ID will always be 4 digits at the end, so we can pluck those last four characters using substr(). When you increment that by one, it will lose its padding. So 0001+1=2. We therefor pad it back using str_pad() with a length of four.
$string = 'PO-12010001';
$id = substr($string, -4, 4);
$newID = $id+1;
$newID = str_pad($newID, 4, '0', STR_PAD_LEFT);
echo "PO-1201".$newID;
Live demo at https://3v4l.org/55RTL
Since it is not clear where the last 4 characters (ID of product) come from, there are 2 different outcomes based on their origin, I am assuming that "PO" is a constant in all your products:
1.If you're auto-generating the Product ID:
$id = "PO-".date('my') . substr(uniqid(), 9, 12);
date('my') will return a two-digits form of the current month and a two-digits form of the current year.
uniqid() returns a unique identifier based on the current time in microseconds, the identifier is usually a mix of letters and digits, and it is usually 13 characters long, so we use substr() to only return the last 4 characters of the string.
NOTE: we are using the last characters of uniqid() because they change every millisecond.
2.If you already have a Product ID:
$id = "PO-".date('my') . $product_id;
When like this situation first how you want to make your ID
Item Type
Month
Year
Product ID
Get product type in your controller
if Product = PO /
Service = SE
Create a New Date using PHP
$date2 = date('Y-m-d');
and get date substring with your requirement and get the last id of the product table and concat all the variable and use as Unique ID.
First, I dopn't know. So maybe it has a similar concept. But anyway, user defined+designed unique are most likely not unique.
My recommendation is to let the database create an unique id with the autoincrement feature. This is usually the only way to guarantee unique ideas in a multi tasking environment.
The, in an second step, you can create an human readable id and use it for displaying it at the suer interface. Such query can be something like:
update table set nice_id = concat("prefix-",main_id)
where main_id = $last_inserted_id
... or any other calculation based on counting the the number of same entries since beginning of month.
There are other solutions based on try to create an nice_id, insert it into the database, and if this fails, create the next one .. and loop until successful. But simple integers created by autoincrement are more performant on queries and for keys.
it's called Human code which can be unique identify beside an Id column in db table.
$idColumn = 1;
$dateCode = date('ym');
$newHumanCode = 'PO-'.$dateCode.substr('0000'.$idColumn, -4);
return $newHumanCode;
also you can use randome number instead of use $idColumn,
for example:
$idColumn = mt_rand();
You can use the Laravel ID generator.
First Install it:
composer require haruncpi/laravel-id-generator
Import the class in your controller.
use Haruncpi\LaravelIdGenerator\IdGenerator;
Now simply use it
$prefix = "PO-".date("my");
$id = IdGenerator::generate(['table' => 'your_table_name', 'length' => 11, 'prefix' =>$prefix]);
Output
PO-12010001
PO-12010002
PO-12010003
...
I have the php query below where I want to count how many times the id exist in a column
$empCount = DB::table('m_employee')->count('group_id')->where('group_id',$idHolder);
VALUES
//tblname is m_employee; column name is group_id and my search variable is $idHolder
Error message is:
{"message":"Call to a member function where() on integer",.......
For this sample, when the value of my $idHolder is 1, the result of $empCount should be 13, if it's 2, result is 3.
And after that, how can I use AND operator from this query :
DB::table('emp')->where('key', $emp)->update([
'id' => $id,
]);
Like where('key', $emp) AND ('monthyear', '06/2018'), basing the date from the cost_date column above (extracting only the month and year) .I'm having hard time on where to insert it.
You can simply use the query below for the count
$empCount = DB::table('m_employee')->where('group_id',$idHolder)->count();
For the AND operator, you can simply chain the where clauses to simulate this
DB::table('emp')->where('key', $emp)->where(DB::raw("(DATE_FORMAT(cost_date,'%m-%Y'))"), '=', '06-2018')->update([
'id' => $id,
]);
Question:
I have merged 5 columns to display in a single column,which the result will look like
name.newname.newname2.newname3.5678
and when some field is empty consider newname3 it'll be like
name.newname.newname2.5678
Now i have to implement a search option which can search for cases like:
1.If someone choose to search for "newname" as search criteria then we should get results basing on comparision of joined string of all five columns.(name.newname.newname2.5678).
2.If someone will search "name.new" it should found "name.name2" as well
Sorting Works Just Fine,Help me with the sql query please.
MyCurrent searchmodel looks like this:
->andFilterWhere(['ilike', '"storeNames"."variantName"', $this->variantName])
->andFilterWhere(['"storeNames"."classId"' => $this->storeClassId])
->andFilterWhere(['"storeNames"."familyId"' => $this->storeFamilyId])
->andFilterWhere(['"storeNames"."platformId"' => $this->storePlatformId])
->andFilterWhere(['ilike', '"storeNames"."subFamilyName"', $this->subFamilyName])
Where columns classId,PlatformId,familyId represents integers that maps to a name and displays some names.
Its the getter function in base model,
public function getStoreName()
{
return $this->hasOne(StoreNames::className(), ['id' => 'storeNameId'])->via('transaction');
}
SO I want to find that if value x is exits between the values of 2 columns or not, For that i have run the query in phpmyadmin :
Normal Approch :-
SELECT * FROM `traits_versions` WHERE 16 BETWEEN `trait_value_lower` and `trait_value_upper` and `style_id` = 1
and it is giving me fine result.But when the same approach i want to find achieve in YII that it is not running and giving the sql error :
YII apprroch :-
$details = array();
$criteria = new CDbCriteria();
$criteria->addCondition('style_id='.$style_id);
$criteria->addCondition('version='.$version);
$criteria->addBetweenCondition($style_contribution,$this->trait_value_lower,$this->trait_value_upper);
$trait_details= $this->find($criteria);
When i debug the query in log than it shows in case of yii :
SELECT * FROM `traits_versions` `t` WHERE ((style_id=1) AND (version=1)) AND (16 BETWEEN NULL AND NULL) LIMIT 1
Why it is giving NULL value in query while i'm passing the name of the column in it.
So please guide me where i'm going wrong in yii.
Add compare condition like below
$criteria->compare('trait_value_lower', 16, false, '>');
$criteria->compare('trait_value_upper',16, false, '<');
instead of between condition
$criteria->addBetweenCondition($style_contribution,$this->trait_value_lower,$this->trait_value_upper);
because between condition will apply on one column as per Yii doc.
public static addBetweenCondition(string $column, string $valueStart, string $valueEnd, string $operator='AND')
I was wondering how to perform something like this:
Table::update(array('position'=>'position+1'));
As far as I know, laravel 4 handles 'position+1' as a string, thus is becomes 0.
I want to perform something like
UPDATE table SET position = position + 1
Can I do that using eloquent?
EDIT: nevermind, doh.."DB::table('users')->increment('votes');"
Simply make use of the increment method:
DB::table('users')->increment('position');
The same is valid for decrement:
DB::table('users')->decrement('rank');
You may even set the second parameter to the amount you want to add/subtract:
DB::table('users')->increment('posts', 5);
DB::table('users')->decrement('likes', 3);
Also, if you need to update other columns along with it, you pass it as the third parameter:
DB::table('users')->increment('range', 3, array(
'name' => 'Raphael',
'rank' => 10
));
And the same goes for Eloquent models, as well:
$firstUser = User::find(1);
$firstUser->increment('height', 0.1, array(
'active' => false
));
you can also do with DB::raw method like this:
DB::table('tablename')->where(your condition)->update(['position' => DB::raw('position+1')]);
you can also do other operations with this like
DB::table('tablename')->where(your condition)->update(['position' => DB::raw('position * 2')]);
This worked fine for me
\Models\User::where("id", $userId)->increment("points");
simply you can use the DB::raw method like this:
Table::update(DB::raw('position=position+1'));