简体   繁体   中英

Dynamic laravel SQL query builder

I'm trying to create a dynamic query with laravel whereby if certain conditions are met it will add to my query. Here is what I have attempted so far. Any guidance please?

    $Tasks = Task::leftJoin('task_recipients', 'tasks.task_id', '=', 'task_recipients.recipient_task_id');

    if ($filterAssignedToMe !== NULL) {
        $Tasks->where('task_recipients.recipient_user_id', '=', $user_id);
    }

    if ($filterAssignedByMe !== NULL) {
        $Tasks->where('tasks.created_by', '=', $user_id);
    }

    $Tasks->groupBy('task_id');
    $Tasks->get();

Here you go:

$Tasks = Task::leftJoin('task_recipients', 'tasks.task_id', '=', 'task_recipients.recipient_task_id');

if ($filterAssignedToMe !== NULL) {
    $Tasks = $Tasks->where('task_recipients.recipient_user_id', '=', $user_id);
}

if ($filterAssignedByMe !== NULL) {
    $Tasks = $Tasks->where('tasks.created_by', '=', $user_id);
}

$Tasks = $Tasks->groupBy('task_id');
$Tasks = $Tasks->get();

Does this work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM