我有一个查询,需要在另一个表“ history”的基础上添加一列(is_found),如果product_id存在于表“ history”上,则列值(is_found)变为1,否则其值保持为0。
这是我的查询:
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'
)
最佳答案
尝试这个:
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')
要么:
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'
);
关于php - 如何基于表添加自定义列-Laravel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59189227/