How to understand pivot?
Hello guys,
I hope you can help me to understand pivot tables.
Currently, I am in a situation where I think I need pivot tables.
I have three tables, one called enduser, one hosts and the last one notes.
hosts have 1 FK
enduser_id
notes have 1 FK
hosts_id
Now I want to get all notes with the enduser id.
So in the normal SQL I would go this way:
SELECT * FROM notes WHERE hosts_ID IN (SELECT id FROM hosts WHERE enduser_id = :id)
How can I make this call in a Laravel way?
Is this really pivot?
You dont need a pivot for this. You can do it with a regular relationship. Lets say your Note model has a relationship called hosts()
$notes = Note::whereHas('hosts', function($query) use ($enduserId) {
$query->where('enduser_id', $enduserId);
});
OK.
I tried it like this:
public function getNotesByUser($id)
{
$notes = Note::whereHas('host', function($query) use ($id) {
$query->where('enduser_id', $id);
});
return response()->json($notes);
}
The model notehas this:
public function host()
{
return $this->belongsTo('\App\Models\Host', 'host_id', 'id');
}
But the return is empty. But there are notes for the host for the enduser
Oh man, I forget ->get()
I am sorry it is working
Please or to participate in this conversation.