Search code examples
sqllaravellaravel-query-builder

Laravel query builder. Column if not null = 1 else = 0 in select method


I using Laravel and its \Illuminate\Database\Eloquent\Builder. I would like to select all columns from "table_1" a have custom column "is_table_2_present" which value will be 1 or 0 depending if(table_1_id != null).

So I would like to do something like that.

$queryBuilder->leftJoin("table_2"....)

$queryBuilder->select([
    "table_1.*",
    "is_table_2_present" = (table_2_id != null) ? 1 : 0,
]);

I was trying to search for an answer but without much of a success. So I would like to ask if something like that is possible?

The reason why I cannot use Eloquent relationship is because I would need relationship with parameter. And that not possible in laravel 5.2 right?

public function table_2($userId)
{
    return $this->hasOne(Table_2::class....)->where(user_id, "=", userId);
}

Solution

  • Since this question kinda died, no respons for a while I solved it with selectRaw() for now. But still in search for more neat solution.

    $queryBuilder->selectRaw("
        table_one.*,
        CASE WHEN table_two.id IS NOT NULL THEN 1 ELSE 0 END AS tableTwoPresent
    ");