Laravel Laravel跨数据库关系哪里出了问题

时间:2020-03-17 14:30:12

标签: laravel

我已经配置了两个数据库连接:

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST', '####'),
            'port' => env('DB_PORT', '####'),
            'database' => env('DB_DATABASE', '####'),
            'username' => env('DB_USERNAME', '####'),
            'password' => env('DB_PASSWORD', '####'),
            'charset' => 'utf8',
            'prefix' => 'pref1_',
            'prefix_indexes' => true,
        ],

        'sqlsrv1' => [
            'driver' => 'sqlsrv',
            'host' => env('DB_HOST1', '####'),
            'port' => env('DB_PORT1', '####'),
            'database' => env('DB_DATABASE1', '####'),
            'username' => env('DB_USERNAME1', '####'),
            'password' => env('DB_PASSWORD1', '####'),
            'charset' => 'utf8',
            'prefix' => '',
        ],

使用普通用户模型和2个自定义模型:

协同作用:

    class Synergy extends Model
    {
        protected $connection = 'sqlsrv1';
        protected $table = 'humres';
        protected $primaryKey = 'res_id';
        public $timestamps = false;

    public function user(){
        return $this->belongsTo('App\User', 'employee_id', 'res_id');
    }

PushNotification:

    class PushNotification extends Model
    {

    public function user(){
        return $this->belongsTo('App\User');
    }

我想检查用户是否具有推送通知权限,以及是否将另一列设置为true。 我尝试使用此查询:

       $users = User::with('PushNotification')->with('Synergy')
            ->whereHas('PushNotification', function($q){
                $q->where('type', 'news')->where('active', 1);
            })
            ->whereHas('Synergy', function($q1){
                $q1->where('freefield20', 1);
            })
            ->get();
        return $users;

它引发以下错误:

SQLSTATE[42S02]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'pref1_humres'. (SQL: select * from [pref1_users] where exists (select * from [pref1_push_notifications] where [pref1_users].[id] = [pref1_push_notifications].[user_id] and [type] = news and [active] = 1) and (exists (select * from [pref1_humres] where [pref1_users].[employee_id] = [pref1_humres].[res_id] and [freefield20] = 1)))

为什么使用 sqlsrv 的前缀而使用 sqlsrv1 却没有输入前缀?

有什么想法可以正确构建此查询吗?

0 个答案:

没有答案