加入多个关系的集合

时间:2013-03-24 17:21:24

标签: model laravel laravel-4 eloquent

给出以下要点:https://gist.github.com/atrauzzi/6674488eb4fbd7a45671

Users have and belong to many Applications.

Applications have many PushMessages.

PushMessages belong to one Application.

我希望能够为用户所关注的每个应用程序获取所有PushMessages。

在要点中查看QueryCode.php,为了让事情有效,我需要改变什么?

2 个答案:

答案 0 :(得分:0)

我将使用PushMessage类来查询它们。

$user = User::find(Auth::user()->id);
$pushMessages = PushMessage::whereIn('application_id', $user->applications()->lists('id'));

答案 1 :(得分:0)

PushMessage::leftJoin(Application::getTable(), Application::getTable().'.id', '=', PushMessage::getTable().'.application_id')->leftJoin(...)->where(Application::getTable().'.user_id','=',1)->select(PushMessage::getTable().'.*')->get();

Eloquent实际上只是将方法调用卸载到流畅的查询构建器。虽然,我建议将这个特定查询包装在一个方法中,或者将它放在一个存储库中