laravelrelationshiphas-many-throughhas-many

How to access drop-down relationships in Laravel



Models :


Tables :

Board :

List :

Task :


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);
    

    Short Form as suggested by @TBAWG:

    $userId = 10;
    $tast = Task::query()
        ->whereHas('list.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.

    I would also suggest using findOrFail($id) instead of find($id) so it return a 404 in case of incorrect id.