简体   繁体   English

MySQL / laravel组查询结果

[英]Mysql / laravel group query results

I am building a laravel 4 based web app that uses a very basic messaging sytem, here is the table structure: 我正在构建一个基于laravel 4的Web应用程序,该应用程序使用了非常基本的消息系统,这是表结构:

messages table
--------------
id int pri
from_user int fk (users table)
to_user int fk (users table)
content text
created_at datetime
updated_at datetime

I am trying to retrieve an array containing all messages grouped by messages.from_user and messages.to_user showing the last message sent or received depending upon the scenario. 我试图检索一个数组,其中包含所有由message.from_user和messages.to_user分组的消息,这些消息根据情况显示了发送或接收的最后一条消息。

Here is the code I have been playing with 这是我一直在玩的代码

$id = Auth::user()->id; 

$messages = DB::table('messages')
      ->join('users', 'users.id', '=', 'messages.from_user')
      ->select(
        'users.id AS from_user_id', 
        'users.first_name AS from_user_name',
        'users.profile_img AS from_user_img',
        'users.alias AS from_user_alias'
      )
      ->where('messages.to_user', '=', $id)
      ->groupBy('messages.from_user')
      ->get();

      foreach ($messages as $single) {
            $last = parent::where('messages.to_user', '=', $single->from_user_id)
                ->orWhere('messages.from_user', '=', $single->from_user_id)
                ->orderBy('created_at', 'DESC')
                ->first();
      }

    // return view make with messages

This code works okey when a users receive a message but as a sender I wont be able to see the conversation until a get a response. 当用户收到消息时,此代码有效,但是作为发件人,直到得到响应,我才能看到对话。

I am also querying the database for each of the grouped messages, I am not quite sure wether that is going to affect performance or not since I am new to mysql web apps. 我也在查询数据库中的每个分组消息,因为我不是mysql Web应用程序的新手,所以我不确定是否会影响性能。

Thanks in advance, Cheers 预先感谢,干杯

http://laravel.com/docs/eloquent 

像与父母一样,在消息表中尝试这种技术!

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

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