whereHas
是可以允许我们向关联来加入 where
的查询约束,但是这里有一个问题,whereHas
是仅支持单条 sql 查询的,也就是说 whereHas
本身是不支持跨库查询的。如果想要学习 whereHas
的用法,可以参考:https://learnku.com/docs/laravel/9.x/eloquent-relationships/12252#d361f0
这几天使用 whereHas
, 遇到了一个问题,如下
举个例子,有这样两个表,分别存在不同的数据库里
database1.A
database2.B
PHP 类如下
class A{
protected $table = 'A';
public function B()
{
return $this->belongsTo(B::class, 'b_id', 'id');
}
}
class B{
protected $table = 'B';
}
然后我们想这样使用
$query = A::query();
$obj->whereHas('B', function ($q) {
$q->where('xxx', xxx)
});
这个时候会报错 Base table or view not found
因为 A表和 B表分别在不同的数据库里,也就是不在同一个数据库里。我们可以把 sql 打印出来
select * from `A` where exists (select * from `B` where `A`.`b_id` = `B`.`id` and `xxx` = xxx)
这样的 sql 肯定跑不通嘛!单条SQL不支持跨库查询
那只能加多一个 数据库前缀,修改的代码如下:
$query = A::query();
$obj->whereHas('B', function ($q) {
$q->from('database2.B')->where('xxx', xxx)
});