Support the ongoing development of Laravel.io →
Eloquent Laravel
0
moderator

The difference is that a whereHas executes one query on the primary connection (like you see in your raw query)

But the with and withCount execute a second query on the connection if your Employee model.

As written in the documentation:

Eloquent does not currently support querying for relationship existence across databases. The relationships must exist within the same database.

A way to work around it is to set the $table property on your Model that includes your database name.

class Employee extends Model
{
    use HasFactory;

    protected $connection = "mysql_2";
    protected $table  = 'mysql_2.employees';

    public function corporate(): BelongsTo
    {
        return $this->belongsTo(Corporate::class);
    }
}

Or if you need more customization (like a dynamic database) you can overwrite the getTable function.

class Employee extends Model
{
    use HasFactory;

    protected $connection = "mysql_2";

    public function corporate(): BelongsTo
    {
        return $this->belongsTo(Corporate::class);
    }

    public function getTable()
    {
        // We ask the database name on the connection and prepare that for the table name with a . in between.
        return DB::connection($this->connection)->getDatabaseName() '.'. parent::getTable();
    }
}

Last updated 1 year ago.

mohinsandhi liked this reply

1

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.