考虑到
this post,
this post和@GiedriusKiršys的回答,我终于想出了一个符合我需求的解决方案,使用以下步骤:
>创建一个返回Model中Relation对象的方法
>急切地在Controller中加载这种新关系
>使用模型中的查询范围过滤掉flag!= 1的电话
在员工模型中
/**
* This is the new relationship
*
*/
public function flaggedTelephones()
{
return $this->telephones()
->where('flag', 1); //this will return a relation object
}
/**
* This is the query scope that filters the flagged telephones
*
* This is the raw query performed:
* select * from mydb1.employees where exists (
* select * from mydb2.telephones
* where telephones.employee_id = employee.id
* and flag = 1);
*
*/
public function scopeHasFlaggedTelephones($query, $id)
{
return $query->whereExists(function ($query) use ($id) {
$query->select(DB::raw('*'))
->from('mydb2.telephones')
->where('telephones.flag', $flag)
->whereRaw('telephones.employee_id = employees.id');
});
}
在控制器中
现在我可以使用这种优雅的语法a’la Eloquent
$employees = Employee::with('flaggedTelephones')->hasFlaggedTelephones()->get();
其内容如下所示:“抓住所有挂着标记电话的员工,然后只接受至少有一部标记电话的员工”
编辑:
在处理了Laravel框架一段时间后(当前版本使用5.2.39),我想,实际上,whereHas()子句在关系模型使用from()方法存在于不同数据库中时可以工作,如它描述如下:
$employees = Employee::whereHas('telephones', function($query){
$query->from('mydb2.telephones')->where('flag', 1);
})->get();
@Rob Contreras声明使用from()方法,但看起来该方法需要将数据库和表作为参数.