在laravel 4中,渴望加载多对多关系


Eager loading with many to many relationship in laravel 4

我正在尝试在laravel 4中设置消息传递系统。我有两个类Conversation和User,它们之间有多对多的关系。我正在输出一个登录用户的对话列表和对话中的用户:

@foreach(User::find(Auth::user()->id)->conversations as $conversation) 
    {{ $conversation->id }}
    @foreach($conversation->users as $user) 
        {{ $user->name }}
    @endforeach   
    <br><br>
@endforeach

这是有效的,并输出会话id,后跟参与该会话的用户的名称。我的问题是,通过这种方式运行了很多查询,我不知道如何使用热切加载,并且仍然能够只选择登录的用户对话。任何帮助都将不胜感激!

编辑:

使用以下代码,我得到了正确的输出,但仍然大量查询数据库:

<?php $user = User::with('conversations')->find(Auth::user()->id); ?>
{{ $user->username }}'s conversations<br><br>
@foreach($user->conversations as $conversation) 
    {{ $conversation->id }} 
    @foreach($conversation->users as $user) 
        {{ $user->name }}
    @endforeach
    <br>
@endforeach

我真的很想能够急切地加载这个部分@foreach($conversation->users作为$user)。它输出:

user_1的对话

1个用户_1个用户_2

5 user_1 user_3

我相信在任何情况下都只有一个用户会话处于活动状态。为什么需要foreach在logged in用户上循环?您的应用程序运行情况如何?

至急切加载:

$user = User::find(Auth::user()->id);
$conversations = $user::with('conversation')->get();

或者正如@David Barker所指出的:

User::with('conversation')->find(Auth::user()->id)

一个对话可能属于许多用户。因此:

$conversation_id = [];
@foreach($user->conversations as $conversation) 
    array_push($conversation_id, $conversation->id);
@endforeach
$conversations_with_users = Conversation::with('user')->whereIn('id', $conversation_id);

现在循环使用$conversations_with_users。