Ad

Laravel Query Builder. Column If Not Null = 1 Else = 0 In Select Method

- 1 answer

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

Answer

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
");
Ad
source: stackoverflow.com
Ad