Laravel 4 Query Builder with different databases - database

I've been using Laravel 4 for a while with success until I found a recent problem. I'm using an alternate DB connection to retrieve a list of products. My problem is that I don't find a way to create a connection like DB::connection('foo') and implement my query in a query builder style. I assume its some IoC behavior but my lack of understanding of the inner framework's code keeps me away from the answer
Thank you all

Add a second connection in app/config/database.php
'mysql2' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
Now use that second connection:
DB::connection('mysql2')->select('where...');

The proper way to accomplish this is DB::connection('mysql2')->table('foo')->join(...)->where(array(...))
My problem was outside the scope of this question.
Thank you all.

Related

How to I specify Tinker to use a different database connection?

I have two database connections. One for my application and another for testing.
In my ..\config\database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'testing' => [
'driver' => 'mysql',
'host' => env('DB_TEST_HOST', 'localhost'),
'database' => env('DB_TEST_DATABASE', 'forge'),
'username' => env('DB_TEST_USERNAME', 'forge'),
'password' => env('DB_TEST_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
I am able to change the database connection in seeding using
php artisan db:seed --database=testing
I wanted to use tinker for the connection 'testing' but unable to change it. Is there any way to change the database connection for tinker similar with database seeding?
As your question starts with using one database for testing/development and one for production, you should look into using different environments, this will allow you to have no change in your code between deployment & local testing.
This task can easily be achieved by specifying your environment:
php artisan tinker --env=local
By default, if you specify no --env, you will be using /your-app/.env
When using local you read variables from /your-app/.env.local
For your specific use case:
php artisan db:seed --env=local
Further reading for Laravel 5.1: https://laravel.com/docs/5.1/configuration
Latest version: https://laravel.com/docs/configuration
NB: You should avoid checking in the ".env" file to VCS, the .env.local should be OK to share, but it is best practice to not bundle production credentials with your VCS.
To set the default database connection to 'mysql_test' from within tinker I use this command:
>>> use DB
>>> DB::setDefaultConnection('mysql_test');
It is especially useful when you want to test your migrations and seeders without messing up your existing (working) local database.
Change default connection
$model_instance = new App\YourModel();
$model_instance->setConnection('new_connection');
$data = $model_instance->find(1);

Existing database integration with Laravel 5.0

I am new to laravel. I've got the whole database designed in phpmyadmin. Now I want to integrate the existing database in Laravel. Is there any way to do that? If so then do I have to create models?
Yes, you can use your database in laravel but at first you have to provide your database credentials to allow the framework/Laravel to access your database. So, you can use a .env file or simply you can use the config/database.php to provide credentials, for example, to use your mySql database all you need to setup the database configuration as follows:
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database_name'),
'username' => env('DB_USERNAME', 'your_database_username'),
'password' => env('DB_PASSWORD', 'your_database_password'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
]
Then regarding your second question, yes, you have to create models for each table or you can use DB facade to run queries directly from your controllers (not recommended). For example, to access your posts table you can create a Post model in app folder which may look something like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
// If your table name is other than posts
// then use this property to tell Laravel
// the table name.
protected $table = 'posts';
}
Then you can use something like this:
$posts = \App\Post::all(); // Get all posts
$post = \App\Post::find(1); // Get the post with id 1
If you don't want to use Eloquent Model like one I've created above then you may use something like this:
$posts = \DB::table('posts')->get(); // Get allp posts
These are some basic examples to get you start. To learn more about the use cases of models/database you should visit Laravel website and read the manual (find Database section and check Query Builder and Eloquent).

CakePHP 2.3 with SqlServer on debian squeeze

I'm confused about all the requirements to get cakephp 2.x to talk to MSSQL (2k8R2). I'm running debian squeeze and installed php5-sybase.
I'd be using this as a second datasource defined as
public $qadb = array(
'datasource' => 'Database/Sqlserver',
'persistent' => false,
'host' => 'xxx.xxx.xxx.xxx',
'login' => 'myuser',
'password' => 'mypass',
'database' => 'mydb',
'prefix' => '',
//'encoding' => 'utf8',
);
When I'm trying to run cake bake with this datasource I get
Error: Database connection "Sqlserver" is missing, or could not be created.
I looked at http://www.php.net/manual/en/ref.pdo-sqlsrv.php which references installing ODBC for linux, but I thought the sybase package would take care of what I need. Any further info anyone has on this would be appreciated.

How can I connect to second database with my cakephp application

my application's requirement is that to display data of magento database table forexample admin_user that is reside at locally connected pc.
so I need to keep as it is my cakephp database values in displaying-modifying-etc, and in only one page magento's database value needs to be printed and updated.
I have kept 2 variables in databse.php
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'myappdatabase',
'prefix' => '',
//'encoding' => 'utf8',
);
var $vsdatabase = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => '192.168.1.36',
'login' => 'root',
'password' => '',
'database' => 'magento',
'prefix' => '',
);
and in controller,
App::import('Model','ConnectionManager');
$db = ConnectionManager::getDataSource('vsdatabase');
$database = $db->config['database'];
$data = $this->User->query("select * from $database.admin_user as t1");
the host I like to keep as written above means default is from my local database and other is remote PC's magento database
If I both host keep same then its working but if write different then It's not working
So I solve this problem?
Plz help me in finding out solution
What you do is plain wrong and even if you would use that code it should belong into a model not a controller.
Simply create a new model named after the magento table, but I would prefix it with magento or something. The model has to be configured to use this db connection.
class MagentoUser extends AppModel {
public $useDbConfig = 'vsdatabase';
}
You can also init models with other aliases and data sources on the fly using ClassRegistry. See http://api20.cakephp.org/class/class-registry#method-ClassRegistryinit
And stay away from using plain SQL queries, you will very likely ending up writing insecure queries and lose other features of the CakePHP ORM.

Using SQLite3 with CakePHP 2.0

I'm trying to run SQLite3 with CakePHP 2.0
In these questions I saw that it's possible to do that in CakePHP 1.3:
- Using Sqlite3 with CakePHP
- How do I connect CakePHP to a SQLite database?
However, the solutions are not valid for CakePHP 2.0.
I configured the file 'database.php' and I got success on the starting page of CakePHP. It was able to connect to the database (but I do not know where to find the .db3 database file).
I used the following code:
public $default = array(
'datasource' => 'Database/Sqlite',
'persistent' => false,
'host' => 'localhost',
'login' => '',
'password' => '',
'database' => 'cake_blog_tutorial',
'prefix' => '',
//'encoding' => 'utf8',
);
I'm trying to find out:
Where should my cake_blog_tutorial.db3 file be kept
Is the datasource different for SQLite3, for example 'Database/Sqlite3'?
Thank you for your help!
In short, the answer is that Sqlite3 databases in CakePHP 2.0 take something like the following configuration:
public $default = array(
'datasource' => 'Database/Sqlite',
'persistent' => false,
'database' => 'database_name',
'prefix' => '',
//'encoding' => 'utf8',
);
The sqlite file is then automatically created in the webroot directory (unless you prepend a relative path to the database name).
Incidentally, you can use in-memory Sqlite databases (for testing purposes, for example) by changing the database name to ":memory:", e.g.:
public $default = array(
'datasource' => 'Database/Sqlite',
'persistent' => false,
'database' => ':memory:',
'prefix' => '',
//'encoding' => 'utf8',
);

Resources