yii2 / Migration Not Working - yii2

public function up() {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
$columns = [
'id' => $this->primaryKey(),
'name' => $this->string(255)->notNull(),
'price' => $this->decimal(10, 2)->notNull()->defaultValue(0),
'original_price' => $this->decimal(10, 2)->notNull()->defaultValue(0),
'special_price' => $this->decimal(10, 2)->notNull()->defaultValue(0),
'comment' => $this->string(10),
'is_deleted' => $this->boolean()->defaultValue(0),
'created_at' => $this->dateTime()->notNull(),
'updated_at' => $this->ti`enter code here`mestamp()
];
$this->createTable('tbl_ironing_order_item', $columns, $tableOptions);
}
i am using yii2 framework, i deploy project on server migrations run working fine, recently create new modules that migrations not run on serve, not showing any error,
How can i run migrations at deploy time?

Make sure that the migration files are on console/migrations directory.
If they are not in that directory, you could specify the directories they are in.
Run
php yii migrate/up --migrationPath=#vendor/path/to/your/migrations

Related

Yii2 migrations - Separated Migrations

I am creating a module with the following structure:
common
L modules
LL blog
LLL backend
LLL frontend
LLL common
LLL migrations
I found in yii2 documentation a section about "Separated Migrations"
In console/config/main.php I have set:
'migrate-blog' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => ['app\common\modules\blog\migrations'],
'migrationTable' => 'migration_blog',
'migrationPath' => null,
]
Then I go to console and run following command:
php yii migrate/create app\\common\\modules\\blog\\migrations\\create_table_blog_post
It returns an error:
Error: Namespace 'app\common\modules\blog\migrations' not found in `migrationNamespaces`
am I missing any settings?
Did you add the following info to config of console.php
'controllerMap' => [
// Migrations for the specific project's module
'migrate-module' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => ['app\module\migrations'],
'migrationTable' => 'migration_module',
'migrationPath' => null,
],
],
I have seen that you have the config in console/config/main.php then the check the yii file is having the following line.
$config = require(__DIR__ . '/console/config/main.php');
After this instead of running
php yii migrate/create app\\common\\modules\\blog\\migrations\\create_table_blog_post
Run the following command
php yii/migrate-blog/create create_table_blog_post
I hope this helps.

How to create and use environment variable .env yii2

I want to create a file .env:
FACEBOOK_CLIENT_ID=*****
FACEBOOK_CLIENT_SECRET=*****
and use variable for config
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'clientId' => env('FACEBOOK_CLIENT_ID'),
'clientSecret' => env('FACEBOOK_CLIENT_SECRET'),
],
I have found the solution.
I use package vlucas/phpdotenv.
Thank for all
You can archive this by Utilizing the enviroment constants. If you are using Yii2 advanced when you initialize your application as dev or production yii sets a constant YII_ENV as either dev or production in your index.php entry script.
If you are using yii basic you can set it as per your enviroment. For example we want to define config for dev.
We will proceed and edit our /web/index.php to
defined('YII_ENV') or define('YII_ENV', 'dev');
Then in our config file we would have the following
'facebook' => [
'class' => 'dektrium\user\clients\Facebook',
'clientId' => (YII_ENV_DEV ? 'Your key when in developent' : 'Your Key if not in developement'),
'clientSecret' => (YII_ENV_DEV ? 'Your key when in developent' : 'Your Key if not in developement'),
],
Refere to this for more details on Enviroment Constants http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#environment-constants
There's a package for Yii2 you can use for dotenv
https://github.com/yiithings/yii2-dotenv
Install:
composer require --prefer-dist yiithings/yii2-dotenv "*"
Usage:
Create a .env in project root directory
DB_HOST="localhost"
DB_NAME="yii2basic"
DB_USER="root"
DB_PASS="YourPassword"
config/db.php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host='. env('DB_HOST') .';dbname='. env('DB_NAME'),
'username' => env('DB_USER'),
'password' => env('DB_PASS'),
'charset' => 'utf8',
];
You could use the dotenv package offered by Symfony. https://symfony.com/doc/current/components/dotenv.html
using it in a PHP file.
use Symfony\Component\Dotenv\Dotenv;
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/.env');
// You can also load several files
$dotenv->load(__DIR__.'/.env', __DIR__.'/.env.dev');
.env file
DB_USER=root
DB_PASS=pass
accessing the variables from the .env file
$dbUser = $_ENV['DB_USER'];
// you can also use ``$_SERVER``

Yii2 - Gii extension assets folder alias referencing to a wrong path

I am trying to learn Yii 2 from a book (Web application development with Yii2 and PHP). Somewhere along the line it instructs me to install gii and create crud files with it.
When I installed with the following command:
php composer.phar require --prefer-dist "yiisoft/yii2-gii:*"
I have following error:
Invalid Parameter – yii\base\InvalidParamException
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/yiisoft/yii2/gii/assets
My bootstrap code:
//Define Yii debug mode
define (YII_DEBUG, true);
//Including composer autoloader
require (__DIR__ . '/../vendor/autoload.php');
//Including Yii framework
require (__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
//debugging for PHP
ini_set('display_errors', true);
//Getting Configuration
$config = require(__DIR__ . '/../config/web.php');
//Include and launch application
(new yii\web\Application($config))->run();
config file:
return [
'id' => 'crmapp',
'basePath' => realpath(__DIR__ . '/../'),
'components' => [
'request' => [
'cookieValidationKey' => 'your secret key here'
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false
],
'db' => require(__DIR__ . '/db.php')
],
'modules' => [
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['192.168.33.1']
]
],
'extensions' => [
require (__DIR__ . '/../vendor/yiisoft/extensions.php')
]
];
extensions file:
$vendorDir = dirname(__DIR__);
return array (
'yiisoft/yii2-bootstrap' =>
array (
'name' => 'yiisoft/yii2-bootstrap',
'version' => '2.0.5.0',
'alias' =>
array (
'#yii/bootstrap' => $vendorDir . '/yiisoft/yii2-bootstrap',
),
),
'yiisoft/yii2-gii' =>
array (
'name' => 'yiisoft/yii2-gii',
'version' => '2.0.4.0',
'alias' =>
array (
'#yii/gii' => $vendorDir . '/yiisoft/yii2-gii',
),
),
);
I digged it a little bit. It seems problem is about the alias of the assets folder.
In GiiAsset.php file, there is this codeblock:
...
class GiiAsset extends AssetBundle
{
public $sourcePath = '#yii/gii/assets';
...
which returns
/var/projectsRoot/crmapp/src/vendor/yiisoft/yii2/gii/assets
but it normally should return
/var/projectsRoot/crmapp/src/vendor/yiisoft/gii/assets
so it is adding an unnecessary yii2 to the path.
I tried to change the $sourcePath in extensions.php file, but changing the value here does not effect the result in any way.
Any ideas?
--UPDATE--
While I was fiddling with things, I tried to define the alias to force the correct value; as follows:
Yii::setAlias('#yii/gii', $vendorDir . '/yiisoft/yii2-gii');
when I try to run the application with this setting I get following error:
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/bower/bootstrap/dist
When I change the alias definition to this:
Yii::setAlias('#yii/gii', $vendorDir . '/yiisoft/yii2-gi');
I get following error:
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/yiisoft/yii2-gi
I'm quite confused with this behavior. What would be causing this?
I ended up with deleting my vendor folder and composer.json file, and creating it back with following content:
{
"require": {
"codeception/codeception": "*",
"fzaninotto/faker": "*",
"yiisoft/yii2": "*",
"yiisoft/yii2-gii": "*"
}
}
When I launched the gii, it again threw the following exception:
The file or directory to be published does not exist:
/var/projectsRoot/crmapp/src/vendor/bower/jquery/dist
I renamed the vendor/bower-asset folder to vendor/bower and it works now.
I probably messed up with something before without noticing, but I'm not certain why it is looking for bower, instead of bower-asset. Renaming the bower-asset to bower seems to solve it.
UPDATE
Thanks to jacmoe from the original Yii forum, it has finally solved.
It seems these two lines need do be present in composer.json in order to automatically create bower folder, instead of bower-asset.
"extra": {
"asset-installer-paths": {
"npm-asset-library": "vendor/npm",
"bower-asset-library": "vendor/bower"
}
}
Original conversation can be found at here:
These lines are automatically created when you install the basic application template, but when installing the bare code base, you need to manually write them.
I have similar problem with my app based on yii2-app-advanced, but separated from #common. Solution is just add vendorPath attribute to application config.

Using SQLite for unit testing a mysql migrations setup

I want to use SQLite for PHPunit tests. We are using the mysql driver, so we have created our migrations based on that... meaning we are using nullables for default values. MYSQL doesn't care about this. SQLite, apparently, does.
Migrations:
Schema::table('users', function ($table) {
$table->string('username', 132)->nullable();
TestCase snippet: configuring phpunit environment
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => ''
]
Running phpunit outputs:
Cannot add a NOT NULL column with default value NULL
I noticed there was a "STRICT" mode for mysql in the database.php configuration file that you can set to false which handles invalid or missing data types:
'mysql' => [
'driver' => 'mysql',
...
'strict' => false,
],
So I started looking for a strict mode for SQLite and found Strict Mode here, tried setting PRAGMA strict=ON; to off
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
'strict' => false
]
But this did not fix it.
Is there a way to set SQLite to ignore nullable() values set in migrations (aimed at mysql configurations) so I can run my unit tests quickly with SQLite in memory?
My alternatives are:
remove all nullable() options for migrations and add defaults, which will take forever
use mysql instead of sqlite, which will be much slower

YII Cannot Find Table

i am working in Yii using WAMP-MYSQL database.i have created tables as-
CREATE TABLE IF NOT EXISTS `balaee_dev`.`country` (
`countryId` INT(11) NOT NULL AUTO_INCREMENT ,
`country` VARCHAR(45) NULL DEFAULT NULL ,
PRIMARY KEY (`countryId`) ,
UNIQUE INDEX `country_UNIQUE` (`country` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
When I test the project here - it's giving me this error:
"The table "country" for active record class "country" cannot be found in the database", though this table exists in database. I am getting this error for each and every controller. Here is my config file:
<?php
// This is the configuration for yiic console application.
// Any writable CConsoleApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'My Console Application',
// application components
'components'=>array(
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
// uncomment the following to use a MySQL database
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=balaee_dev',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
),
);
And i have main.php as-
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'My Balaee Application',
// preloading 'log' component
'preload'=>array('log'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
'application.modules.KnowledgePortal.*',
'application.modules.QuestionBank.*',
//'application.modules.UserAuthentication.*',
'application.plugins.*',
'application.extensions.noaaWeather.*',
),
'modules'=>array(
//Question Bank Module
'QuestionBank'=>array(),
//Social Networking Module
'SocialNetworking'=>array(),
//Knowledge Portal Module
'KnowledgePortal'=>array(),
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'root',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
//'ipFilters'=>array('204.93.172.30'),
),
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
'mailer' => array(
'class' => 'application.extensions.mailer.EMailer',
'pathViews' => 'application.views.email',
'pathLayouts' => 'application.views.email.layouts'
),
'curl'=>array(
'class' => 'application.extensions.curl.Curl',
),
'params'=>array(
'noaaWeather.cachePath' => 'protected/extensions/noaaWeather/cache'
),
// uncomment the following to enable URLs in path-format
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
/*
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
*/
'db'=>array(
//'connectionString' => 'mysql:host=localhost;dbname=balaee_dev',
'connectionString' => 'mysql:host=204.93.172.30;dbname:shailani_balaee_dev',
//'emulatePrepare' => true,
'username' => 'shailani_bdev',
'password' => 'nTRXpfuH8wmjx5hV',
'charset' => 'utf8',
),
// uncomment the following to use a MySQL database
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=balaee_dev',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
/*
array(
'class'=>'CWebLogRoute',
),
*/
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster#example.com',
),
);
So please can someone guide me what changes i need to make?
You say you're using MySQL. So the sqlite line in your configuration shall not appear.
Provided the tables have been actually created in your MySql database (I guess you can see them in MySQL Workbench or in PHPMyAdmin):
remove this line
re-run the model / CRUD / whatever generation.
If your connection string and params are OK, it should work.
If it doesn't, feel free to copy here the related errors logs : Yii, MySql and Apache's logs can contain useful information.