php - GroupBy and OrderBy Laravel Eloquent -
building chat application dashboard , trying notification of last message other user sent.
here model relationships:
public function messages() { return $this->hasmany('app\message', 'author_id'); } public function lastmessage() { return $this->hasmany('app\message', 'recipient_id')->orderby('created_at', 'desc')->groupby('author_id'); } on thing cant figure out instead of returning last message should sorted using orderby, returns first record of group exists in database.
looked around online cant seem find info on this. thing found post said orderby , groupby in laravel don't play together.
any appreciated!
instead of redefining relationship in lastmessage, might try calling messages , running query that.
without seeing more of model schema (ie: these relationships defined??), might not perfect, it's start:
public function lastmessage() { return $this->messages() // <-- notice ()...this creates query instead of returning relationship ->where('recipient_id', $this->id) // not sure if correct, might need adjust according how have defined tables ->orderby('created_at', 'desc') ->first(); } it query messages relationship chained constraints listed. , returning first() returns 1 record opposed collection.
Comments
Post a Comment