php - Laravel 中的自定义查询

标签 php mysql laravel laravel-5 laravel-query-builder

如何为多个表编写查询,例如

"select  items.id, items.name, sum(qty) as qty  from dispatch_main 
    inner join dispatch_detail on dispatch_main.id = dispatch_detail.id
    inner join items on items.id = dispatch_detail.item_id
    left outer join customers on dispatch_detail.customer = customers.id
    where dispatch_main.entry_type in ('Purchase','Return','Confirmed') and 
    dispatch_main.to_=$location and items.for_customer in ($types)
    group by dispatch_detail.item_id
    order by  items.id
    ";

或者

"select items.id, items.name, sum(qty) as qty  from dispatch_main 
    inner join dispatch_detail on dispatch_main.id = dispatch_detail.id
    inner join items on items.id = dispatch_detail.item_id
    left outer join customers on dispatch_detail.customer = customers.id
    where dispatch_main.entry_type in ('Dispatch','Confirmed') and 
    dispatch_main.from_=$location and items.for_customer in ($types)
    group by dispatch_detail.item_id
    order by  items.id
    "

在 Laravel 5.4 中? DB::statement 可以运行这种类型的查询吗?如果我在 DB::statement(''); 中编写相同类型的查询

最佳答案

  1 DB::table('dispatch_main')
  2   ->innerJoin('dispatch_detail', 'dispatch_main.id', '=', 'dispatch_detail.id')
  3   ->innerJoin('items', 'dispatch_detail.item_id', '=', 'items.id')
  4   ->leftJoin('customers', 'dispatch_detail.customer', '=', 'customers.id')
  5   ->whereIn('dispatch_main.entry_type', ['Purchase','Return','Confirmed'])
  6   ->where('dispatch_main.to_', $location)
  7   ->whereIn('items.for_customer', $types)
  8   ->groupBy('dispatch_detail.item_id')
  9   ->orderBy('items.id')
 10   ->get()->toArray();
 11
 12

尝试这个,并且永远、永远避免编写 RAW 查询,直到你绝对这样做。

关于php - Laravel 中的自定义查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45483932/

相关文章:

php - Yii $this->renderPartial() in widget Action throw error

mysql - 如何使用另一个数据库中的数据来选择数据?

php - 每天、每周和每月的总和

php - 返回路线 View 而不是 Controller

php - Laravel 5 输入旧为空

php - 将 HTML 转换为 ENML

php - 错误 "Check the manual that corresponds to your MySQL server version for the right syntax to use near"

php - 在 php 中的 Android post 请求

php - 在 Bitbucket 上分发我的 php 库的正确方法

php - 如何从文本输入中将id插入数据库