Laravel Query Builder - 如何使用连接格式化查询

时间:2017-07-06 17:03:14

标签: php laravel join laravel-query-builder

我知道这是一个写得不好的查询。如何使用“Laravel查询”构建器重新编写此代码?

SELECT tgi.rate, tgi.tax_types_id, tt.name, tt.sales_chart_master_id, tt.purchase_chart_master_id  
FROM tax_group_items tgi, tax_types tt 
WHERE tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2) 
AND tt.id = tgi.tax_types_id 
AND tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))

2 个答案:

答案 0 :(得分:0)

如果您在模型类中发布关系,答案会更容易和更清晰。如果您不知道如何定义关系,请转到官方文档的查询构建器部分。 如果您不想定义关系或不想使用它们,请使用此

$query = DB::select('your query');

答案 1 :(得分:0)

DB::table(DB::raw('tax_group_items tgi, tax_types tt'))
    ->select(['tgi.rate', 'tgi.tax_types_id', 'tt.name', 'tt.sales_chart_master_id', 'tt.purchase_chart_master_id'])
    ->whereRaw('tgi.tax_groups_id = (SELECT tax_groups_id FROM customers WHERE id=2)')
    ->where('tt.id', 'tgi.tax_types_id')
    ->whereRaw('tt.id NOT IN (SELECT tax_types_id FROM item_tax_type_exemptions WHERE item_tax_types_id = (SELECT item_tax_types_id FROM products WHERE id = 1))')
    ->get();