I have the following situation. I want to build some Models to use on different prior configured databases. In this case I have a model named Category which should work on a few tables on a Magento 2 database. I want to reuse that model for different databases. Here is the simplified model:
namespace AppModelsMagento;
use IlluminateDatabaseEloquentModel;
class Category extends Model
{
protected $attributeIds = [];
protected $table = 'catalog_category_entity';
protected $primaryKey = 'entity_id';
protected $fillable = ['entity_id', 'store_id', 'website_id'];
}
If I set the property $connection to my desired database, I can use the ->all() method and get a wonderful Collection of entries. But as mentioned, to use it on different databases, all the best practises show two options, the static and non-static way. Both are not working for me.
The static way (->on(‘MY_CONNECTION’)) results in still using the default connection and not my connection. If I use the non-static way (->setConnection(‘MY_CONNECTION’)) it also goes to the default connection. If I do a dd() on the model right before the ->all() it says $connection = ‘MY_CONNECTION’. But as soon as I run it, it’s the default connection again.
$categoryAggegator = new MagentoCategory;
$categoryAggegator->setConnection('MY_CONNECTION');
//dd($categoryAggegator); // Here it is MY_CONNECTION
$categories = $categoryAggegator->all();
// Here it throws an exception, because the table is not present in the default connection
Any ideas?
2
Answers
in your config/database.php add a new array item inside "connections" array.
And now in your model file you can mention the connection name
protected $connection = 'mysql2';
If you want to change on fly then use
MagentoCategory::on('mysql2')->get();
If you are working with two different databases (not just schemas within the same database), you will need to establish two separate connections. This is because SQL queries execute within a single connection, meaning you cannot reference two databases or connections in a single query. Additionally, it’s not possible to define foreign keys between two separate databases at the database level.
As a result, you cannot directly define relationships between Eloquent models if their underlying tables reside in separate databases. Instead, you’ll need to handle them independently by running separate queries. Laravel allows you to assign a specific connection to each model.
However, if by "database" you actually mean a different schema within the same server, then it’s possible to work across schemas. In this case, you can specify the schema name as part of the table name in your model.