Laravel:我该如何获取那些急于加载的元素,并把它们都放到一个数组中呢?


Laravel : How do I fetch just the eager-loaded element and put them all in an array?

我有两个模型—conversationsuser和events—它们以多对多的关系相关联。我想急于加载事件,并把它放在一个数组。我怎么做呢?


这些是我的模型和它们之间的关系。

ConversationsUser

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

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

控制器(到目前为止我所做的)

    $loginuser = Auth::user();
    $convUsers = ConversationsUser::with('Events')->where('user_id','LIKE',$loginuser->id)
                 ->has('events');
    $events = $convUsers->get()->fetch('events')->toJson();
意外结果

[
   [
      {
        "event_id":3
        "conversaitons_id":1
      }
   ],
   [
      {
        "event_id":5,
        "conversations_id":23
      },
      {
        "event_id":6,
        "conversations_id":23
      }
   ]
]

首选结果

[
      {
        "event_id":3
        "conversations_id":1
      },
      {
        "event_id":5,
        "conversations_id":23
      },
      {
        "event_id":6,
        "conversations_id":23
      }
]

我建议用另一种方法,像这样:

$conversation_ids = ConversationsUser::whereUserId($loginuser->id)->get(['conversations_id'])->toArray();
$events = Events::whereIn('conversations_id', $conversation_ids);