当我在shell中使用raw查询时,我正在使用laravel Query Builder连接mysql数据库中的两个表
SELECT * from parent_accounts
LEFT JOIN child_accounts on parent_accounts.account_id=child_accounts.parent_id
结果
使用laravel查询构建器时,如下所示
$accounts=\DB::table('parent_accounts as p')->join('child_accounts as c','p.account_id','=','c.parent_id')->select('p.name AS parent','c.name as name','c.account_id as account_id','c.parent_id as parent_id')->get();
我从来没有得到第四行,如果我先使用左连接和child_accounts,结果不是这样吗?
发布于 2017-10-19 21:33:12
尝试使用查询构建器的方法leftJoin(),因为在您的SQL查询中,您正在进行左连接,例如:
$accounts= DB::table('parent_accounts as p')
->leftJoin('child_accounts as c','p.account_id','=','c.parent_id')
->select('p.name AS parent','c.name as name','c.account_id as account_id','c.parent_id as parent_id')
->get();
发布于 2017-10-19 21:31:35
如果您对Laravel DB查询逻辑有一些问题,您可以执行原始的sql requests或使用更简单的版本,如this
例如:
$accounts= \DB::select(\DB::raw("
SELECT * from parent_accounts
LEFT JOIN child_accounts on
parent_accounts.account_id=child_accounts.parent_id");
但是,如果您真的想了解您的问题所在,我建议您将DB查询转换为sql,并查看您的请求是否相同。更多here。
TLDR;
只需在查询的末尾添加->toSql()
并读取输出。然后将laravel查询转换为与其SQL版本相同的查询。
https://stackoverflow.com/questions/46830869
复制相似问题