Laravel:我如何只获取预先加载的元素并将它们全部放入数组中?

时间:2014-08-04 08:42:08

标签: php laravel laravel-4 eloquent

我有两个模型--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
      }
]

1 个答案:

答案 0 :(得分:2)

我建议反过来做,就像这样:

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