user7435594
user7435594

Reputation:

Is it possible to relate the same table using "hasMany" in laravel?

I kinda stuck here while creating a chat system using Laravel I have created the table to store message like this

inbox_message
->id (PK)
->message
->sentTo
->belongsTo
->isStarred
->isRead
->isDraft
->group_message_id (FK) in the same table (inbox_messages).

Now, group_message_id will work as FK with reference to ID (both FK and PK are in same table)

For fetching I've implemented hasMany relationship like this

public function child(){
    return $this->hasMany(message::class,'group_message_id','id');
}

Now, instead of getting all the message within child I'm getting [] array in child and getting all messages separately like this.

[
    {
        "id": 2,
        "message": "msg2 by patient6 to doctor 3",
        "belongsTo": 6,
        "sentTo": 3,
        "isStarred": 0,
        "isDraft": 0,
        "isRead": 1,
        "group_message_id": 1,
        "created_at": "2017-09-05 03:48:19",
        "updated_at": "2017-09-05 06:52:33",
        "deleted_at": null,
        "child": []
    },
    {
        "id": 4,
        "message": "msg4 by patient6 to doctor 3",
        "belongsTo": 6,
        "sentTo": 3,
        "isStarred": 0,
        "isDraft": 0,
        "isRead": 1,
        "group_message_id": 1,
        "created_at": "2017-09-05 03:54:35",
        "updated_at": "2017-09-05 06:52:33",
        "deleted_at": null,
        "child": []
    }
]

The query I did to fetch the results

$userMsgs = message::with( [
                    'child' => function ( $query ) {
                        $query->where( 'isDraft', '!=', 1 );
                    }
                ] )->where( 'isDraft', '!=', 1 )
                                   ->where( 'sentTo', $authId )
                                   ->get();

Question is it possible to relate same table in eloquent if yes then please let me know where I'm wrong?

Thanks for the help I'm in much need :)

Upvotes: 1

Views: 4214

Answers (1)

Meera Tank
Meera Tank

Reputation: 719

Try Using Self Relation

class message extends Eloquent {

   function child(){
       return $this->hasMany('message', 'group_message_id');
   }
}

Hope This will Help.

Upvotes: 2

Related Questions