简体   繁体   中英

How to add custom column based on a table - Laravel

I have a query in which I need to add a column (is_found) on the base of another table "history", if product_id exists on a table "history" then the column value (is_found) became 1 otherwise its value remains 0.

Here is my query:

Product::select(
    'products.id as product_id',
    'products.name',
    'products.desc',
    'products.image',
    'products.barcode',
    'categories.name as category_name',
    'categories.id as category_id',
)
    ->leftJoin(
        'categories',
        'products.category_id',
        '=',
        'categories.id'
    )

Try this:

Product::select(
    'products.id as product_id',
    'products.name',
    'products.desc',
    'products.image',
    'products.barcode',
    'categories.name as category_name',
    'categories.id as category_id',
    \DB::raw('IF(history.product_id, 1, 0) AS is_found')
)
    ->leftJoin(
        'categories',
        'products.category_id',
        '=',
        'categories.id'
    )
   ->leftJoin('history', 'products.id','=','history.product_id')

Or:

Product::select(
    'products.id as product_id',
    'products.name',
    'products.desc',
    'products.image',
    'products.barcode',
    'categories.name as category_name',
    'categories.id as category_id',
    \DB::raw('IF((select product_id from history where history.product_id = products.id), 1, 0)')
)
    ->leftJoin(
        'categories',
        'products.category_id',
        '=',
        'categories.id'
    );

You can use sub-select with exists

Product::select(
    'products.id as product_id',
    'products.name',
    'products.desc',
    'products.image',
    'products.barcode',
    'categories.name as category_name',
    'categories.id as category_id',
)
->selectRaw('exists (select * from history where history.product_id = products.id) as is_found')
->leftJoin('categories', 'products.category_id', '=','categories.id')

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