I have 2 controllers, ContentController for general user and ManageController for administrator. I need to change the connection from default to admin and I have this code in my database.php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => '',
'database' => 'ComputerScience',
'prefix' => '',
'encoding' => 'utf8',
);
public $admin = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'admin',
'password' => '',
'database' => 'ComputerScience',
'prefix' => '',
'encoding' => 'utf8',
);
}
Thank you
So, inside your Model, you would use the useDbConfig Attribute:
class Example extends AppModel {
public $useDbConfig = 'admin';
}
Inside your Controller, simply use:
$this->ModelName->useDbConfig = 'admin';
Thats all.
I would use Model::setDataSource() rather than just setting the database config var. This is because there are other possible changes that come with changing the datasource:
$this->Model->setDataSource('admin');
Related
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.
In a controller I want to change the default database so i can access the new db (db2) from anywhere in the website. The db2 database has the same models but just different data. My code just accesses the other database but doesnt set the new default database to db2 which can be accessed anywhere in the website. I didnt get the answer from the below posts.
This is my controller :
$connection = ConnectionManager::get('db2'); // 'db2' where my second database is configured
$results = $connection->execute('SELECT * FROM tutors')->fetchAll('assoc');
//this works but doesnt set the default database to db2 everywhere
This is my app.php :
'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
//'port' => 'non_standard_port_number',
'username' => 'root',
'password' => '',
'database' => 'aptutori_test',
'encoding' => 'utf8',
'timezone' => '+11:00',
'flags' => [],
'cacheMetadata' => true,
'log' => false,
'quoteIdentifiers' => false,
'url' => env('DATABASE_URL', null),
],
'db2' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
//'port' => 'non_standard_port_number',
'username' => 'root',
'password' => '',
'database' => 'aptutori_testbak',
'encoding' => 'utf8',
'timezone' => '+11:00',
'flags' => [],
'cacheMetadata' => true,
'log' => false,
'quoteIdentifiers' => false,
'url' => env('DATABASE_URL', null),
],
Dynamically change database connection in cakephp 3
http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database
Use ConnectionManager::alias():
http://api.cakephp.org/3.0/class-Cake.Datasource.ConnectionManager.html#_alias
Fore example this will make all tables that require the default connection to use db2:
ConnectionManager::alias('db2', 'default');
You could do this application wide in a Middleware in > cake 3.3, opposed to using a DispatcherFilter, like described in http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database.
<?php
namespace App\Middleware;
use Cake\Datasource\ConnectionManager;
class TenantShardMiddleware
{
public function __invoke($request, $response, $next)
{
$tenant = $request->getHeader('MY-tenant');
ConnectionManager::alias($tenant[0], 'default');
$response = $next($request, $response);
return $response;
}
}
In my example above I'm using a special Request Header to switch databases.
Hello I am new to cakephp 2. I want to know, how to connect to database in one controller and loop for each. Please help me with details.
I have already set the following in the database config:
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'db_one',
'prefix' => '',
//'encoding' => 'utf8',
);
public $database2 = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'db_announcement',
'prefix' => '',
//'encoding' => 'utf8',
);
You should research bit more in google before asking question here.
Anyways, CakePHP takes default database connection which is there in database.php in core folder, so all your queries which you execute in the database which is defined in default vairable in database.php and if you want to connect multiple database than you can try something like this.
In your database configuration file:
public $database2 = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '*******',
'database' => '*****',
'prefix' => '',
'encoding' => 'utf8',
);
And in your controller you can have connection in this way:
$db = ConnectionManager::getDataSource('user');
$list = $db->rawQuery('your query'); or customized CakePHP queries can work here too
I hope you will get your answer from this.
Thanks
$i=0;
$total=$list->fetchAll(PDO::FETCH_ASSOC);
instead of getDataSource method I would suggest to use $this->ModelName->setDataSource('mongo');
E.g If you want to fetch the data from User model of 'mongo' database source , which you have mentioned in database.php, then to set that it would look like.
$this->User->setDataSource('mongo')
in database.php you are having following code
public $mongo = array(
'datasource' => 'Mongodb.MongodbSource',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'root',
'database' => 'mongo_data',
'prefix' => '',
'encoding' => 'utf8',
);
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
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