Home > OS >  Laravel WhereHas with two separated databases
Laravel WhereHas with two separated databases

Time:12-22

Hello I have a problem when I try to make a query to another database.

I have 3 tables: "MarketAgreement" and "MarketTransaction" in the koop_app (mysql) database and the "AgreementEnergia" table in the koop_app_energia database

My Models:

enter image description here

enter image description here

enter image description here

With the "MarketAgreement" model, WhereHas works perfectly for me, but with "AgreementEnergia" I get this error:

enter image description here

I have declared which database each table belongs to but still when I try to do the whereHas crossed between "AgreementEnergia" (found in the koo_app_energia database) and "MarketTransaction" (found in the koop_app database) Laravel tries to find the table in the wrong database.

How can I solve that? Thanks a lot.

CodePudding user response:

I have solved it by simply changing protected $table = 'market_transactions'; for protected $table = 'koop_app.market_transactions';

CodePudding user response:

For a "belongsToMany" relationship, You can do something like that:

public function your_method()
{
    $database = $this->getConnection()->getDatabaseName();

    return $this->belongsToMany('B', "$database.a_bs", 'a_id', 'b_id');
}

BUT: when you are modelling relationships between data, it implicitly within the same database. It is not expected to do this in two different databases

For a "Has" relationship, Eloquent does not currently support querying for relationship existence across databases. The relationships must exist within the same database (https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence)

PS: please do not put screenshots, but code snippets

  • Related