laravel DB查询选择多个表而不加入

时间:2018-05-18 01:46:55

标签: php laravel

我在这里有一个Raw SQL查询以及如何在laravel查询构建器中编写这个Raw查询

以下是原始查询:

SELECT tbl_stock.* , series.*, series_size.*, tbl_size.* FROM 
tbl_stock , series, series_size, tbl_size 
WHERE
tbl_stock.series_id = series.series_id AND 
tbl_stock.size_id = series_size.size_id AND
tbl_stock.size_id = tbl_size.size_id

我已经尝试了DB Query构建器laravel但是获得了异常

$stock_info = DB::table(['tbl_stock', 'shades'])->get();

这给了我这个

  

数组到字符串转换异常

感谢提前

1 个答案:

答案 0 :(得分:1)

首先,您应该用现代语法替换您的古老连接语法:

SELECT
    t1.*,
    t2.*,
    t3.*,
    t4.*
FROM tbl_stock t1
INNER JOIN series t2
    ON t1.series_id = t2.series_id
INNER JOIN series_size t3
    ON t1.size_id = t3.size_id
INNER JOIN tbl_size t4
    ON t1.size_id = t4.size_id;

然后,使用Laravel的查询构建器语法在PHP代码中构建查询:

$stocks = DB::table('tbl_stock')
    ->join('series', 'tbl_stock.series_id', '=', 'series.series_id')
    ->join('series_size', 'tbl_stock.size_id', '=', 'series_size.size_id')
    ->join('tbl_size', 'tbl_stock.size_id', '=', 'tbl_size.size_id')
    ->select('tbl_stock.*', 'series.*', 'series_size.*', 'tbl_size.*')
    ->get();