没有获得未付款或部分付款的记录,有人可以帮助我吗?

问题描述 投票:0回答:1
$draw = intval($request->draw);
$start = intval($request->start);
$length = intval($request->length);
$order = $request->order;
$search = $request->search;
$search = $search['value'];
$col = 0;
$dir = "";
if (!empty($order)) {
  foreach ($order as $o) {
    $col = $o['column'];
    $dir = $o['dir'];
  }
}

if ($dir != "asc" && $dir != "desc") {
  $dir = "desc";
}
$valid_columns = array(
  0 => '',
  //   1=>'vendor',
  1 => 'confirmed_at',
  2 => 'invoice',
  3 => 'client_name',
  4 => 'total_amount',
  5 => '',
  6 => '',
  7 => '',
  8 => '',

);
if (!isset($valid_columns[$col])) {
  $order = null;
} else {
  $order = $valid_columns[$col];
}
if($os_only == 1)
{
    $sales = Sale::selectRaw('sales.*, sum(sales_payments.payment_amount) as paid')
        ->join('sales_payments', 'sales.invoice', '=', 'sales_payments.invoice')
        ->where('invoice_status', 1)
        ->groupBy('sales.invoice');
        ->havingRaw('sales.total_amount < paid');
}
else
{
      $sales = Sale::select('sales.*', 'clients.client_name')
    ->where('invoice_status', 1)
    ->join('clients', 'sales.client_id', '=', 'clients.uid');
}

if (!empty($search)) {
  $x = 0;

  foreach ($valid_columns as $sterm) {
    if (!empty($sterm)) {

      if ($x == 0) {
        // $this->db->like($sterm,$search);
        $sales->where($sterm, 'LIKE', '%' . $search . '%')->where('invoice_status', 1);
      } else {
        // $this->db->or_like($sterm,$search);
        $sales->orWhere($sterm, 'LIKE', '%' . $search . '%')->where('invoice_status', 1);
      }
      $x++;
    }
  }
}
if ($order != null) {
  $sales->orderBy($order, $dir);
} else {
  $sales->orderBy('uid', 'DESC');
}

  $query = $sales->offset($start)->limit($length)->get();

我想在 $query 中获取未付款或部分付款的记录 如果 $os_only = 1 我不想要全额付款的记录 注意:付款记录在 sales_ payment 中是多个或单个,或者如果没有发票付款,则 sales_ payment 中没有记录凭这张发票。我怎样才能做到这一点,我没有得到结果,有人可以帮助我做错了什么吗?

mysql laravel join payment invoice
1个回答
0
投票

尝试修改查询:

if($os_only == 1)
{
   $sales = Sale::selectRaw('sales.*, IFNULL(SUM(sales_payments.payment_amount), 0) as paid')
    ->leftJoin('sales_payments', 'sales.invoice', '=', 'sales_payments.invoice')
    ->where('invoice_status', 1)
    ->groupBy('sales.invoice')
    ->havingRaw('sales.total_amount > paid');
}
else
{
    $sales = Sale::select('sales.*', 'clients.client_name')
    ->where('invoice_status', 1)
    ->join('clients', 'sales.client_id', '=', 'clients.uid');
}

说明:

  • IFNULL(SUM(sales_ payments. payment_amount), 0) 确保如果 sales_ payments 中没有付款,则已付款额将被视为 0。
  • 使用
  • leftJoin,以便没有付款的发票也出现在查询结果中。
  • havingRaw('sales.total_amount >paid') 用于过滤未付款或部分付款的发票记录。
© www.soinside.com 2019 - 2024. All rights reserved.