If you catch errno: 150 “Foreign key constraint is incorrectly formed” when you try to create a new table in mySQL(or another relational DB) then you can use a simple way to find a bad foreign key(s). Just execute this query:
REFERENCED_TABLE_NAME = '<your table name here>' OR TABLE_NAME = '<your table name here>';
After that you can see where this bad table using and you can go and delete bad foreign key(s).
For get random item from your model in yii2 you can use:
Fast and simply solution is:
$item = YourModel::find()->orderBy('rand()')->one();
$item = YourModel::find()->orderBy(new Expression('rand()'));
Sometimes you need to update your latest added field in DB table by random numbers.
For that reason you can use this simple SQL command:
[1 – min, 100-max]
SET `columnName` = FLOOR( 1 + RAND( ) *100 );
In this way you can easy update `columnName` by random value in defined range.
Happy SQLing… Continue reading UPDATE with random number between range 1-n [MYSQL UPDATE RAND]
Suppose you have a table in the database where the stored data and you need to check or get that dates but with the changes – calculate directly by MySQL.
Example, you want to get users end dates (7-day licence after registration):
SELECT `register_date`, `uid`,
DATE_ADD(`register_date`, INTERVAL 7 DAY) AS `end_date`
Perfect, now you can show for user that his licence if over `end_date`…
In addition, you can subtract the required number of days
Continue reading How to add one/two/n days or hours to date in MySQL (DATE_ADD in MYSQL)
If you need show $query in Yii 2 like one line SQL string for debug then you can write this:
You can use the 2 main functions
LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.