I'm trying to count unread messages in laravel app, however my "last_viewed" column contains "raw" time in seconds stored in "last_viewed (int) 11" and my "created_at" contains mysql timestamp so I can't compare them in mysql statement. Here is how I compare them, but it's kind of spaghetti
class Helper {
public static function count_unread_messages()
{
$result = Conversation::join('messages','messages.conversation_id','=','conversation.id')
->join('conversation_members','conversation_members.conversation_id','=','conversation.id')
->select('conversation_members.last_viewed as last_viewed',
'messages.created_at as created_at')
->where('conversation_members.user_id','=',Auth::user()->id)
->groupBy('messages.id')->get();
$i = 0;
foreach ($result as $key) {
if (date($key->last_viewed) < date(strtotime($key->created_at))) {
$i++;
}
}
return $i;
}
}
but I'd like to compare inside Mysql statement, like that ->where('last_viewed' ,'<', 'created_at')->count()
Is there a way to change format of a timestamp into seconds inside a mysql statement?
FROM_UNIXTIME(), see documentation here: dev.mysql.com/doc/refman/5.5/en/…. You're going to have to useDB::raw()statements, by the way. Good luck! :)UNIX_TIMESTAMP()- documentation here: dev.mysql.com/doc/refman/5.5/en/…. Although you can compare either seconds or dates directly, it'll result in the same thing. That said, do you really store in timestamp - not in datetime?