繁体   English   中英

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

[英]Laravel : In a many-to-many relationship between A and B, how to get all B's from multiple A's?

在普通的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方法。

这些是我的模特及其关系

对话用户

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

大事记

public function conversations(){
    return $this->belongsToMany('ConversationsUser');
}
$conversations = ConversationsUser::with('events')->whereUserId($loginuser->id)->get();

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

更新

实际上,有一个技巧可以更轻松地实现这一目标:

$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.*']);

这将完全返回您所需要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM