如何在Laravel Jenssegers Mongodb ORM中进行原始查询?

时间:2018-03-28 21:00:22

标签: mongodb laravel

我正在使用Laravel和jessenger mongodb(https://github.com/jenssegers/laravel-mongodb),我在mongodb中有以下对象集合:

用户:(身份证,姓名,电子邮件)

消息(from_id,to_id,text)

我需要在两个集合上运行以下查询:

db.User.aggregate([
   {
     $lookup:
       {
         from: "Message",
         localField: "id",
         foreignField: "from_id",
         as: "user_message"
       }
  }
  ,{$match:{id:1}}
])

我想知道的是如何在jesenger laravel(ORM /面向对象的风格)中做到这一点......通常我会做Message::where('from_id', '=', $user->_id)->get(['to_id']) ....等...但我该如何运行或翻译以上查询?感谢。

1 个答案:

答案 0 :(得分:0)

在您的用户模型中,您可以使用embedsMany定义与消息的关系:

/**
 * messages that were received by the user
 */
public function messagesSent() 
{
    return $this->hasMany(User::class, 'from_id');
}


/**
 * Messages that were sent to the user
 */
public function messagesReceived() 
{
    return $this->hasMany(User::class, 'to_id');
}

您还希望在messages模型上建立关系,以指明sender/receiver是谁,以便您可以急切加载这些:

public function sender()
{
    return $this->belongsTo(User::class, 'from_id');
}

您也可以定义接收器:

public function receiver()
{
    return $this->belongsTo(User::clas, 'to_id');
}

现在,如果您想要从上到下发布最新消息,请不要使用User模型来定义此消息,请从Message模型开始,这样您就不会尝试订购通过关系,在你的情况下更容易不:

Message::with(['sender'])
    ->where('from_id', $user->id)
    ->limit(20)
    ->orderBy('created_at')
    ->take(50);

如果您只想加载加载了senders关系的用户的所有邮件:

User::with(['messagesReceived', 'messagesReceived.sender'])
    ->where('id', $user_id)
    ->firstOrFail();