How to use Join in BD Query Laravel using two different databases? - php

I got this piece of code bellow to show a table in a page, but it doesn't work. I got this error where says that the command was denied.
$posts = DB::connection('mysql2')
->table('wp_rocketsciencebrposts')
->join('users', 'users.rsbwordpressid', '=', 'wp_rocketsciencebrposts.post_author')
->select('ID', 'post_title', 'post_status', 'post_author', 'post_date', 'users.name')
->whereIn('post_status', ['publish', 'private'])
->where('post_type', 'post')
->orderBy('id', 'desc')
->paginate(15, ['*'], 'posts');
SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command
denied to user 'lovel095_heaven'#'177.134.6.23' for table 'users'
(SQL: select count(*) as aggregate from wp_rocketsciencebrposts
inner join mysql.users on users.rsbwordpressid =
mysql2.wp_rocketsciencebrposts.post_author where post_status
in (publish, private) and post_type = post)
Both databases are on the same server.
The table "wp_rocketsciencebrposts" comes from "lovel095_rocketsciencebr" database.
The table "users" comes from "lovel095_centralrsb" database.
In my .env file i git this:
DB_CONNECTION=mysql
DB_HOST=br862.hostgator.com.br
DB_PORT=3306
DB_DATABASE=lovel095_centralrsb
DB_USERNAME=(myusername)
DB_PASSWORD=(mypassword)
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=br862.hostgator.com.br
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=lovel095_rocketsciencebr
DB_USERNAME_SECOND=(myusername)
DB_PASSWORD_SECOND=(mypassword)
In my config>database.php file, i got this:
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'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'),
]) : [],
],
'mysql2' => [
'driver' => env('DB_CONNECTION_SECOND'),
'host' => env('DB_HOST_SECOND'),
'port' => env('DB_PORT_SECOND'),
'database' => env('DB_DATABASE_SECOND'),
'username' => env('DB_USERNAME_SECOND'),
'password' => env('DB_PASSWORD_SECOND'),
],
Pls, help!

Most of database is not support a cross database join, I believe SQL server support it but it must be on the same server. Instead of forcing your application to joining two different database, just simply use the database separately.
In your case, simply select the posts first, then select the user name using foreach. Here's the workaround :
$posts = DB::connection('mysql2')
->table('wp_rocketsciencebrposts')
->select('ID', 'post_title', 'post_status', 'post_author', 'post_date')
->whereIn('post_status', ['publish', 'private'])
->where('post_type', 'post')
->orderBy('id', 'desc')
->paginate(15, ['*'], 'posts');
foreach ($posts as $key => $post){
$user = DB::connection('mysql')
->table('lovel095_centralrsb')
->where('id', $post->post_author)
->first();
$posts[$key]->post_author_name = $user->name;
}

Hello I'm not sure you need to configure 2 databases to execute that kind of query.
Just make sure the credentials you are using to connect to one database is able to access both, it works with MySql.
From here i suggest you read that other stackoverflow answer
Basically you need to prefix tables with database name for the join to work.
I suggest you first try this from PhpMyAdmin then translate into Laravel Query Builder.
Remember that you can use entire raw queries in the Query builder, like :
DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = '$someVariable'") );

Related

Laravel - Join tables across 2 databases (same server)

I'm trying to join 2 tables in 2 databases. But using the common solutions don't seem to be working and I can't figure out why. Here is what I have:
My connections:
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'data'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => env('DB_SCHEMA', 'public'),
],
'auth' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE_AUTH', 'authentication'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => env('DB_SCHEMA', 'public'),
]
The Laravel query I'm trying to run:
Files::where('sender_id',$userId)
->join('authentication.users as users','Policies.sender_id','=','users.id')
->select('*')
->get();
The table Files belong to database data.
But this gives me an error SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "authentication.users" does not exist
I know the connection to the authentication table works since I can do this
DB::connection('auth')->table('users')->whereIn('id', '123')->first();
I've tried replacing authentication with auth but to no avail.
What am I doing wrong? Thanks.
Using query builder :
$query = DB::table('database1.table1 as dt1')->leftjoin('database2.table2 as dt2', 'dt2.ID', '=', 'dt1.ID');
$output = $query->select(['dt1.*','dt2.*'])->get();
using Eloquent model option:
Model1::where('postID',$postID)
->join('database2.table2 as db2','Model1.id','=','db2.id')
->select(['Model1.*','db2.firstName','db2.lastName'])
->orderBy('score','desc')
->get();
This might be a duplicate ask. Pls refer Join two MySQL tables in different databases on the same server with Laravel Eloquent

Why $results = DB::select works while DB::table is not?

I have this mysql driver
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', '{database}'),
'username' => env('DB_USERNAME', '{user}'),
'password' => env('DB_PASSWORD', '{pass}'),
'unix_socket' => env('DB_SOCKET', ''),
'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'),
]) : [],
],
and in my database.php
I have 'default' => env('DB_CONNECTION', 'mysql'),
So When I run in the controller
$results = DB::table('adventureworks2017.sales.store')->get()-first();
It gives me error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.`store`' at line 1 (SQL: select * from `adventureworks2017`.`sales`.`store`)
while
$results = DB::select('SELECT * FROM adventureworks2017.`sales.store` limit 5'); it workes
Any reason why query builder is not working wile passing statement works?
You can try passing a raw expression for the table name so the query builder doesn't try to decipher your dot notation into database and table, I suppose.
DB::table(DB::raw('sales.store'))->first();
Or even
DB::table(DB::raw('`sales.store`'))->first();

Syntax error or access violation: 1140 Mixing of GROUP columns laravel

I have written this query with pagination in it
$items = Item::select('items.*', 'sub_category_name', 'category_name', 'sub_category_slug', 'category_slug')
->join('sub_categories AS sc', 'sc.sc_id', 'items.sub_category_id')
->join('categories AS c', 'c.category_id', 'sc.category_id')
->where('items.is_active', '=', 1)
->where('sc.is_active', '=', 1)
->where('c.is_active', '=', 1)
->where('sc.sc_id', '=', $sub_category_id)
->paginate(1);
But it says
Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
But when I add ->groupBy('item_id'); it says
Syntax error or access violation: 1055 'books.items.item_name' isn't in GROUP BY
But when I do item_name in groupBy clause it says to groupBy the next column. Why?
When you use aggregate functions like MIN(),MAX(),COUNT() AVG() you have to use Group BY
But in latest MYSQL u have to use all the columns in select as a group By too.
In your config/database.php turn off the strict mode.
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'strict' => false after that you can use group by on a single column too.
You can comment ONLY_FULL_GROUP_BY line in modes array

Laravel groupBy not working , version 5.4.24

Here is my query, it works on all older versions.
$data = DB::table('applicant')
->groupBy('AppAffID')
->get();
Error i get is :
SQLSTATE[42000]: Syntax error or access violation: 1055 'comloant_loantreeAPI.applicant.AppID' isn't in GROUP BY (SQL: select * from `applicant` group by `AppAffID`)
I have tried the database change :
I added 'strict' => false, to database config.
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
What is it that you want to achieve with the groupBy? If you want to sort on the AppAffID you should use the orderBy instead done like so:
$data = DB::table('applicant')
->orderBy('AppAffID', 'desc') //can also use 'asc' for ascending
->get();

Group by not working after upgrading to laravel 5.3

This is the code that was working on laravel 5.2
$menus = CmsMenuItem::groupBy('menu_id')->get();
but now it throws error
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1
of SELECT list is not in GROUP BY clause and contains nonaggregated
column 'convertifier_cms.cms_menu_items.id' which is not functionally
dependent on columns in GROUP BY clause; this is incompatible with
sql_mode=only_full_group_by (SQL: select * from 'cms_menu_items' group
by 'menu_id')
I have also tried
`strict => false`
in database.php but no effect
Try this for database config.
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
and use query like this way
$menus =DB::table('cms_menu_item')
->select('*')
->groupBy('menu_id')
->get();
As per this PR just try this in your database config
'strict' => false,
If not there is some known issue is going on.
Please refer these links PR & Issue
Please Go to your config/database.php folder. In mysql configuration array, change strict => true to strict => false, and everything will work nicely.

Categories