laravel 5连接MySQL_在Laravel 5.2中使用多个MySQL数据库连接查询关系存在

考虑到

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()方法,但看起来该方法需要将数据库和表作为参数.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值