Models :
-
USER
- boards() : HasMany
-
BOARD
- lists() : HasMany
-
LIST
- tasks() : HasMany
-
TASK
Tables :
Board :
- id
- user_id
List :
- id
- board_id
Task :
- id
- list_id
How do I want to search for a task with an ID, but without creating a relationship in USER?
I can create a relationship in USER called tasks(), but I do not want to do this in this way. I want, for example:
$user = User::find(10);
$task = $user->boards()->lists()->tasks()->find($id);
Note that the tasks and lists table do not have a user_id field, only the board table
I TRY : $task = $user->boards()->lists()->tasks()->find($id);
>Solution :
Go the other way, start with what you want to get.
$userId = 10;
$tast = Task::query()
->whereHas('list', function($list) use ($userId) {
$list->whereHas('board', function($board) use ($userId) {
$board->where('user_id', $userId);
});
})
->find($id);
You, of course, need the reverse relations of what you shared in your question.
- Task -> list
- list -> board
I would also suggest using findOrFail($id) instead of find($id) so it return a 404 in case of incorrect id.