nirvair
nirvair

Reputation: 4180

Relationship between a hasMany and belongsToMany in Laravel

I have two Models - InternalNotesThread and InternalNotes

class InternalNotesThread extends Model {

public function notes(){

        return $this->hasMany('App\InternalNotes', 'thread_id', 'id');
    }
}

class InternalNotes extends Model {

public function thread() {

        return $this->belongsTo('App\InternalNotesThread');
    }
public function users()
    {
        return $this->belongsToMany('App\User', 'user_notes_tagged', 'internal_notes_id', 'user_id');
    }
}

Also, InternalNotes is mapped to User with a relation of belongsToMany.

DB Structure:

internal_notes_thread:
id - int
ticket_id (FK) - int
name - string

internal_notes:
id - int
thread_id (FK) - int
notes - string

user_notes_tagged: (Many to many with internal_notes and User)
internal_notes_id (FK) - int
user_id (FK) - int

For every note, there might be some user tagged in it.

How can I directly relate this relationship with the internal_notes_thread???

I get the data with this:

$data = InternalNotesThread::with('notes')->where('ticket_id', '=', $id)->get()->toArray();

But, in the notes array, I am not able to get the users tagged in that note

How can I get all the data in one go???

Upvotes: 2

Views: 203

Answers (1)

Ben Claar
Ben Claar

Reputation: 3415

You're not eager loading the users, so they don't show up in your ->toArray() array.

Try this:

$data = InternalNotesThread::with('notes.users')
    ->where('ticket_id', '=', $id)
    ->get()
    ->toArray();

Upvotes: 3

Related Questions