Yii : multiple databases connection fails - database

i read the yii docs and the following code should work;
well, it doesnt. :))
db is the primary database
db1 and db2 are the secondary databases
what is wrong here ?
the website is online, at www.linkbook.co, and it cant connect to any of the databases
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=linkbookco',
'emulatePrepare' => true,
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'tablePrefix' => '',
),
'db1' => array(
'connectionString' => 'mysql:host=localhost;dbname=linkbookco1',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'tablePrefix' => '',
'class' => 'CDbConnection' // DO NOT FORGET THIS!
),
'db2' => array(
'connectionString' => 'mysql:host=localhost;dbname=linkbookco2',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'tablePrefix' => '',
'class' => 'CDbConnection' // DO NOT FORGET THIS!
),

db is the predefined component of Yii, so bedefault CActiveRecord makes connection using db. So for other components you have created using CDbConnection class you have to activate connection for them externally.
SO You need to overwrite getDbConnection() method of CActiveRecord.
Extend the CActiveRecord for specific database connection like db1.
Save this as Db1CActiveRecord.php and place in components directory.
<?php
/**
*
* Used for db1 database connection
*
*/
class Db1CActiveRecord extends CActiveRecord {
private static $db1 = null;
public function getDbConnection()
{
if (self::$db1 !== null)
return self::$db1;
else
{
self::$db1 = Yii::app()->db1;
if (self::$db1 instanceof CDbConnection)
{
self::$db1->setActive(true);
return self::$db1;
}
else
throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
}
}
}
Now you need to use Db1CActiveRecord for the model class of database db1.
Like:
class Db1Model extends Db1CActiveRecord{
......
}
Implement this way for both db1 & db2 database.

Related

databse not configured error while insert record in laravel

I configured second database in laravel with name Test. but when i used to insert data in second database's table. It shows me an error, database not configured please help me to find where is my mistake?
I already make configuration to add new database in project. i changed .env file and database.php file in config folder. but nothing can help me.
database.php
'mysql2' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'database' => 'Test',
'username' => 'root',
'password' => '',
'unix_socket' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
.env
DB_CONNECTION_SECOND=mysql2
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=Test
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=
SellerSelectProduct.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SellerSelectProduct extends Model
{
protected $connection = 'Test';
protected $fillable = ['product_id'];
public function product(){
return $this->belongsTo(Product::class);
}
}
SellerBaseController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
use App\SellerSelectProduct;
class SellerBaseController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function someMethod()
{
$someModel = new SellerSelectProduct;
$someModel->setConnection('Test');
$something = $someModel->find(1);
return $something;
}
}
SellerProductController.php
<?php
namespace App\Http\Controllers;
use App\City;
use App\State;
use Illuminate\Http\Request;
use App\SellerSelectProduct;
class SellerProductController extends SellerBaseController
{
public function someMethod()
{
$someModel = new SellerSelectProduct;
$someModel->setConnection('Test');
$something = $someModel->find(1);
return $something;
}
public function index(State $state)
{
return $state->Cities;
}
public function addproducts(Request $request){
SellerSelectProduct::insert($request->data);
return response()->json([
'message' => 'Selected product list updated successfully'
]);
}
}
a sample of a second conection.
.env
DB_CONNECTION=mysql2
DB_HOST2=127.0.0.1
DB_PORT2=3306
DB_DATABASE2=
DB_USERNAME2=
DB_PASSWORD2=
database.php
'mysql2' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST2', ''),
'port' => env('DB_PORT2', '3306'),
'database' => env('DB_DATABASE2', 'forge'),
'username' => env('DB_USERNAME2', 'forge'),
'password' => env('DB_PASSWORD2', ''),
'unix_socket' => env('DB_SOCKET2', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
To have an effect on clean or cache changes with or optimize handmade php command.

Laravel - Set up dynamic database connection on Multi tenant application

Within my app I have different businesses and those have a number of users.
For example:
Business A has UserA, UserB and UserC
Business B has UserD and UserE
And so on..
Each business has its own separate database, so Users A, B and C access the same database, and Users D and E access a different database (Every tenant database is identical in structure, the only thing that differs is the data).
There is a main database that has this information for each user, so I know which database a user belongs.
'main' => array(
'driver' => 'mysql',
'host' => 'hostname',
'database' => 'main_database',
'username' => 'username',
'password' => 'password',
'prefix' => '',
),
'tenant' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => DYNAMIC_DATABASE_NAME_GOES_HERE,
'username' => 'username',
'password' => 'password',
'prefix' => '',
),
I need to find a way to do the following in Laravel:
User signs in to the app
After login I get the user database identifier/database name using the main database connection
Set that specific database name within a connection called "tenant"
App uses that tenant connection to load the data of that specific
user/business
How can I accomplish this in Laravel 5.4?
This link has a very good example of what you are looking for.
1) Setup two connections in your database config.
'main' => array(
'driver' => 'mysql',
'host' => 'hostname',
'database' => 'database',
'username' => 'username',
'password' => 'password',
'prefix' => '',
),
'tenant' => array(
'driver' => 'mysql',
'host' => '',
'database' => '',
'username' => '',
'password' => '',
'prefix' => '',
)
2) Then to switch the DB, put the following code in your filters or middleware. Considering you have Tenant model for database connection info.
$tenant = Tenant::whereSubDomain($subdomain)->first();
Config::set('database.connections.tenant.host', $tenant ->host);
Config::set('database.connections.tenant.username', $tenant ->username);
Config::set('database.connections.tenant.password', $tenant ->password);
Config::set('database.connections.tenant.database', $tenant ->database);
//If you want to use query builder without having to specify the connection
Config::set('database.default', 'tenant');
\DB::purge('tenant');
\DB::reconnect('tenant');
dd(\DB::connection('tenant'));
3) Specify following in your models
//On models dealing with the main DB
protected $connection = 'main';
//On models dealing with tenant DBs
protected $connection = 'tenant';

Cakephp delete not working for multiple DB connect

I am using cakephp 2.4 , am working on a project which uses two db connections based on the user logged in. while accessing the second DB and Retrieve data it is working fine, but when i delete record in the second DB table record its throw error as ..
Invalid catalog name: 1046 No database selected
Can anyone help on this ...
this is my DB connect code
$this->default['host'] = 'localhost';
$this->default['login'] = 'xxxxxx';
$this->default['password'] = 'xxxx';
$this->default['database'] = 'xxxxx';
$this->default['prefix'] = 'xxxx_';
if(!empty($_SESSION['subsites'])){
$this->test['host'] = 'localhost';
$this->test['login'] = 'xxxx';
$this->test['password'] = 'xxxxx';
$this->test['database'] = 'ccxxxx';
$this->test['prefix'] = 'xxxx'.'_';
}
then we used $useDBconfig ='test'; in model
Define multiple database configuration in app/config/database.php as
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'db1',
'prefix' => '',
//'encoding' => 'utf8',
);
public $subSites = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'db2',
'prefix' => '',
//'encoding' => 'utf8',
);
Now when you want to switch to subSites config just write following code:
$this->Model->useDbConfig = $subSites;
You can use $useDbConfig Attribute inside your Model.
class Example extends AppModel {
public $useDbConfig = 'user';
}
Inside your Controller, simply use:
$this->ModelName->useDbConfig = 'user';
for More Details, please click on http://book.cakephp.org/2.0/en/models/model-attributes.html

Variable database setting Cakephp

I'm searching a way to create a variable database in Cakephp.
I'm creating a website in wich the database setting (user, pass, db) depends of the user who logg's in. The database settings come from another database.
Thanks in advance,
AƤron
-- ANSWER
Thanks for your quick reply.
I know how to switch between databases, but the database settings have to be variable.
Example
$db = $this->DB_SET['DB_SET']['db']; //from model DB_SET the database
$db_login= $this->DB_SET['DB_SET']['login'];
$db_host= $this->DB_SET['DB_SET']['host'];
$db_pass= $this->DB_SET['DB_SET']['pass'];
var $db2 = array(
'driver' => 'mysql',
'persistent' => false,
'host' => $db_host,
'login' => $db_login,
'password' => $db_pass,
'database' => $db,
'prefix' => '',
'encoding' => 'UTF8',
'port' => '',
);
If you're looking to create database connections on the fly, you may want to use ConnectionManager::create().
// get logged in user's id and create a connection for them
$id = $this->Auth->user('id');
ConnectionManager::create("user_$id_db", array(
'driver' => 'mysql',
'persistent' => false,
'host' => $db_host,
'login' => $db_login,
'password' => $db_pass,
'database' => $db,
'prefix' => '',
'encoding' => 'UTF8',
'port' => '',
));
Then set your models to use it when you're ready.
// get logged in user's id and use their connection
$id = $this->Auth->user('id');
$this->Model->setDataSource("user_$id_db");

How I will access a table from another Databse in cakephp

I have two database in my project.
I have declared two connection variable in database.php. As follows:
var $development = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'xxxx',
'login' => 'xxxx',
'password' => 'xxxx',
'database' => 'yyyy',
'prefix' => '',
);
var $production = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'xxxxxx',
'login' => 'xx',
'password' => 'xx',
'database' => 'xxx',
'prefix' => '',
);
Now I am using the development as the default connection.
In one controller function I need to fetch some values from the anther DB. How can I get the other DB data there?
If any body can help regarding this I will very very obiliged to him/her.
Thank you in advance .
you can use $useDbConfig in your model class to define which database should it use for data source
class Example extends AppModel {
var $useDbConfig = 'development';
}
class Example extends AppModel {
var $useDbConfig = 'production';
}
and you can check the detail usage in cakephp document
http://book.cakephp.org/view/1057/Model-Attributes

Resources