我正在处理以下情况:我有两个模型,一个Employee
with id
and name
字段和一个Telephone
with id
, employee_id
and flag
字段。还有一个一对多关系在这两种模型之间,即一个员工可能拥有多部电话,而一部电话可能属于单个员工。
class Employee extends Model
{
public function telephones()
{
return $this->hasMany(Telephone::class);
}
}
class Telephone extends Model
{
public function employee()
{
return $this->belongsTo(Employee::class);
}
}
The Employee
模型引用表employees
存在于名为的数据库模式中mydb1
,而Telephone
模型与一个相关telephones
存在于名为的不同数据库模式中的表mydb2
.
我想要的是仅获取员工与至少一部电话特定标志的急切加载,使用 Eloquent 并且(如果可能)不使用查询构建器
到目前为止我尝试过的without成功是:
1)在Controller中使用whereHas方法
$employees = Employee::whereHas('telephones', function ($query) {
$query->where('flag', 1); //Fetch only the employees with telephones of flag=1
})->with([
'telephones' => function ($query) { //Eager load only the telephones of flag=1
$query->where('flag', 1);
}
])->get();
我在这里尝试做的首先是仅检索拥有 flag=1 电话的员工,其次是仅急切加载这些电话,但我得到以下结果查询异常由于使用了不同的数据库连接:
未找到基表或视图:表 mydb1.telephones 不存在(这是真的,电话存在于 mydb2 中)
2) 控制器中带有约束的渴望加载
$employees = Employee::with([
'telephones' => function ($query) {
$query->where('flag', 1);
},
])->get();
此方法急切地加载 flag=1 的电话,但它返回all员工实例,这不是我真正想要的。我想要一个集合仅具有电话的员工型号 with flag
= 1,排除具有telephones = []