I am using Symfony 7.1 to develop my API backend.
In my .env
:
DATABASE_URL="mysql://root:[email protected]:3306/rsywx?serverVersion=8"
BLOG_URL="mysql://root:xxxxxxxx$@xxxx:3306/wordpress?serverVersion=8"
(One local, one remote.)
In my doctrine.yaml
:
octrine:
dbal:
connections:
default:
url: '%env(resolve:DATABASE_URL)%'
blog:
url: '%env(resolve:BLOG_URL)%'
# IMPORTANT: You MUST configure your server version,
# either here or in the DATABASE_URL env var (see .env file)
#server_version: '16'
profiling_collect_backtrace: '%kernel.debug%'
use_savepoints: true
default_connection: default
orm:
default_entity_manager: default
entity_managers:
default:
connection: default
blog:
connection: blog
#auto_generate_proxy_classes: true
#enable_lazy_ghost_objects: true
#report_fields_where_declared: true
#validate_xml_mapping: true
#naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
#auto_mapping: true
#mappings:
# App:
# type: attribute
I have commented out many other configurations to keep it bare minimum.
In my controllers, I like to use raw sql to fetch records.
public function summary(Connection $connection):JsonResponse
{
$sql_book='select count(id) bc, sum(page) pc, sum(kword) wc from book_book';
$sql_visit='select count(vid) vc from book_visit';
$summary=$connection->fetchAssociative($sql_book);
$visit=$connection->fetchAssociative($sql_visit);
$res=[
'bc'=>$summary['bc'],
'pc'=>$summary['pc'],
'wc'=>$summary['wc'],
'vc'=>$visit['vc'],
];
return new JsonResponse($res);
}
This works fine and Symfony uses the default
database.
In another controller, I have to fetch records from another db:
public function summary(Connection $connection):JsonResponse
{
$sql='select ....';
...
}
How do I get connection to my 2nd db?
Thanks!