Laravel:在A和B之间的多对多关系中,如何从多个A中获得所有B?

时间:2014-08-04 04:38:40

标签: php laravel laravel-4 eloquent

在正常的many2many教程中,我们学习了如何通过A->B()从单个特定A中获取所有B。如果你想从多个A中获得所有B,该怎么办?我想到的第一件事就是使用for循环但如果我们不想使用for循环呢?


这是我的情况: 我有两个模型,ConversationsUser和Events。现在我想从多个ConversationsUser模型中获取所有事件而不使用for循环

这是我对问题的初步看法:

$loginuser = Auth::user();
ConversationsUser::where('user_id','LIKE',$loginuser->id)->events();

但它不起作用,因为找不到events方法。

这些是我的模特和他们的关系

ConversationsUser

public function events(){
    return $this->belongsToMany('Events');
}

事件

public function conversations(){
    return $this->belongsToMany('ConversationsUser');
}

2 个答案:

答案 0 :(得分:3)

$conversations = ConversationsUser::with('events')->whereUserId($loginuser->id)->get();

$events = $conversations->lists('events')->collapse()->unique();

答案 1 :(得分:1)

<强>更新

实际上有一种方法可以更轻松地实现这一目标:

$events = null;

ConversationsUser::where('user_id','LIKE',$loginuser->id)
                                      // note the reference
  ->with(['events' => function ($q) use (&$events) {
    $events = $q->get();
  }])->get();

$events;            // all related models with `->pivot` attached (possible dups)
$events->unique();  // unique related events

con :它会运行其他查询

专业:这很容易使用


最简单易行的事情是whereIn

根据关系类型,您可能需要连接,例如在这种情况下(为简洁起见,我使用短变量名称):

$convUsers = ConversationsUser::where('user_id','like',$loginuser->id)->get();
$convUsersIds = $convUsers->modelKeys();

// or if you don't need those models but only their ids:
$convUsersIds = ConversationsUser::where('user_id','like',$loginuser->id)->lists('id');

$events = Events::join('PIVOT_TABLE as ce', 'ce.event_id', '=', 'events.id')
   ->whereIn('ce.conversation_id', $convUsersIds)
   ->get(['events.*']);

这将完全返回您所需的内容。