Rev Tech
Rev Tech

Reputation: 63

How to GroupBy in Relationship?

I have post table

| ID | TITLE | SLUG | CONTENT | COMMENTS_COUNT | 

and i have post_reactions table

| ID | USER_ID | TYPE | POST_ID | 

I want to make a relationship that what reactions that post have

Upvotes: 0

Views: 652

Answers (3)

Yugma Patel
Yugma Patel

Reputation: 627

You can use callback function for grouping your relations describe at below.

  Post::with(['post_reactions' => function($query){
        $query->groupBy('TYPE');
  }])->get();

Upvotes: 1

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

You can directly do it by model.

public function postrelation()
{
    return $this->hasMany(PostRelation::class)->groupBy('type');
}

Or

Post::with(['postrelation' => function($q){
    $q->groupBy('type');
}])->get();

Upvotes: 1

Ankush Sood
Ankush Sood

Reputation: 421

You can make relation with the help of follwing syntax in the Model Class

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model {

/**
 * Get the phone record associated with the user.
 */
    public function phone(){
        return $this->hasOne('App\Phone');
    }
}

Upvotes: 0

Related Questions