Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LANDE_FINANCE's avatar

Group by polymorphic relation

Hi guys, Again i need yours help..

class Comment extends Eloquent {

    public $table = 'comments';

    public static $rules_review = ['content' => 'required'];

    public static $rules_messages = ['required' => 'This field is required'];

    public $fillable = ['user_id', 'name', 'content'];

    public function dynamic() {
        return $this->morphTo();
    }

    public function user() {
        return $this->belongsTo('User');
    }

}

class Review extends Eloquent {

    public $table = 'reviews';

    public $fillable = ['user_id', 'guest_id', 'slug', 'title'];

    public $dates = ['created_at'];

    public static $sluggable = array(
        'build_from' => 'title',
        'save_to'    => 'slug',
        );

    public function category() {
        return $this->belongsTo('ReviewCategory');
    }

    public function user() {
        return $this->belongsTo('User');
    }

    public function comments() {
        return $this->morphMany('Comment', 'dynamic');
    }
}
$comments = Comment::with('dynamic')->orderBy('created_at', 'desc')->take(5)->get(); // ->groupBy('dynamic.company_title')

I need to get last 5 comments ordered by creation date with review, but (with unique review by company_title) review should not repeated..

0 likes
1 reply
LANDE_FINANCE's avatar
Comment::with('dynamic')->groupBy('dynamic_id')->orderBy('created_at', 'desc')->take(5)->get()

Solved. Thanks.

1 like

Please or to participate in this conversation.