Skip to content

Eloquent/Model::withCount doesn't specify database/schema name #23042

@foreshadow

Description

@foreshadow
  • Laravel Version: 5.5.33
  • PHP Version: 7.1.8
  • Database Driver & Version: Mysql 5.7

Description:

Eloquent/Model::withCount doesn't specify database/schema name

I have 2 models User and Problem. Their table locates in different database/schema in same server (users locates in connection mysql a.k.a. schema acm, problem locates in connection mysql2 a.k.a. schema boj in my case).
I have defined protected $connection for these two models. Anything other works well.
And when I call User::with('solved') it works well, but when calling User::withCount('solved'), the generated sql sentence doesn't specify the problem table's database/schema, which will cause an error.

(formatted)

(3/3) QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'acm.problem' doesn't exist (SQL: 
select `users`.*, (
    select count(*) from `problem` 
    inner join `boj`.`solution` on `problem`.`problem_id` = `boj`.`solution`.`problem_id` 
    where `users`.`id` = `boj`.`solution`.`acm_user_id` and `boj`.`solution`.`result` = 4
) as `solved_count` 
from `users` order by `active_at` desc limit 150 offset 0)

Steps To Reproduce:

Defines

class User
{
    protected $connection = 'mysql';
    // some other defines 

    public function solved()
    {
        $mysql2 = config('database.connections.mysql2.database');
        return $this
            ->belongsToMany(Problem::class, "$mysql2.solution", 'acm_user_id', 'problem_id')
            ->wherePivot('result', 4);
    }
}

I believe it doen't matter where the solution table locates and how I call it... Although it may looks ugly.

class Problem
{
    protected $connection = 'mysql2';
    protected $table = 'problem';
    // some other defines
}

Call

User::with('roles')->withCount('solved')->orderBy('active_at', 'desc')->paginate(150);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions