vendredi 18 mars 2016

join query one to many relations in Laravel 5.1

Hello friends, I have three tables with one to many relationship. Three tables as follows

1.name: event_invoice columns: Id,InvoiceCode,GrandTotal 2.name:payments columns:id,invoice_id,amount 3.name:invoiceduedates columns:id,invoiceid,amount,duedate

and table data like below

event_invoice  table data
 id invoicecode amount
327 ide-2016327 7500
payment table data
id invoice_id received_amount 
1  327         7461
2  327         50
invoiceduedates table data
id invoiceid amount
1  327        3750
2  327        3750

and here is the join query but giving wrong results

DB::table('event_invoice')

        ->where( DB::raw('year(DueDate)'), $year)->where('event_invoice.Status','=','1')
        ->join('invoiceduedates', 'event_invoice.Id', '=', 'invoiceduedates.invoiceid')
        ->join('payments', 'event_invoice.Id', '=', 'payments.invoice_id')
        ->select(DB::raw('
            event_invoice.Id,
            event_invoice.GrandTotal,
            event_invoice.InvoiceCode, 
            payments.invoice_id,sum(payments.recieved_amount) +sum(payments.adjust_amount)  as amount,
            count(payments.invoice_id) as no,
            invoiceduedates.date as invoiceduedate,
            count(invoiceduedates.invoiceid) as no
            '))

        ->groupBy('event_invoice.InvoiceCode')
        ->get();

Here is result

  +"Id": 327
    +"GrandTotal": "7500.00"
    +"InvoiceCode": "IDE-E031- 2016326"
    +"invoice_id": "327"
    +"amount": 15178.0
    +"payments": 4
    +"invoiceid": "327"
    +"invoiceduedates": 4

So after running this query i should suppose to get payments as number in 2 and invoiceduedates as 2 but its giving 4.Even when i executed the same query in mysql its giving the same result .

please help me out

Thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire