2

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

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
Alwin Kesler
  • 1,450
  • 1
  • 20
  • 41

2 Answers2

4
  1. 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'    => '',
    
  2. Now use that second connection:

    DB::connection('mysql2')->select('where...');

Laurence
  • 58,936
  • 21
  • 171
  • 212
  • Yes, that what the documentation says.. but what I want is something like `DB::connection('mysql2')->table('foo')->join(...)->where(array(...))` in a Query Builder fashion – Alwin Kesler Jul 10 '13 at 16:32
  • The example I put above it's pseudocode and doesn't work. With @shift answer all I can do is write a SQL command between quotes in the select method. What I want (and now I think can't be done) is not to loose the Query Builder properties when working with extra db connections. It doesn't have any sense to me to use a string query if you already have Eloquent and query builder there to help you – Alwin Kesler Jul 10 '13 at 17:22
  • @AlwinKesler you can do that. See [my answer here](http://stackoverflow.com/questions/17410049/laravel-4-connect-to-other-database/17412301#17412301), which I think Shift copied from? - My answer has some more details on doing what you'd like. You actually answered your own question. After setting up the config for another MySQL connection, you can then use `DB::connection('mysql2')->table('foo')->join(...)->where(array(...))` exactly as you said. **Note** that you can't do Joins across different DBs. – fideloper Jul 10 '13 at 21:45
  • Are you saying `DB::connection('mysql2')->table('foo')...` gives you an error? – fideloper Jul 10 '13 at 21:47
  • I found the problem.. my "pseudocode" guess was right. The problem was with the foreign server which had a mysql 4.1+ password issue that I was attributing to the laravel alternative connection. Thank you all – Alwin Kesler Jul 11 '13 at 16:19
3

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.

Alwin Kesler
  • 1,450
  • 1
  • 20
  • 41