2

I have run a join query based on client_id between directsales and clients table. but when i print the query result it's show duplicated data.

here, is my code.

public function readirectsalereport(Request $request)
{
    $client_id=$request->client_id;
    $fromdate=$request->frmdate;
    $todate=$request->todate;

        $dsale=DB::table('directsales')
            ->join('clients','directsales.client_id','=','clients.id')
            ->select('clients.client_name','clients.addr')
            ->where('directsales.client_id','=',$client_id)
            ->get();

            return $dsale;

}

and it's show this result.

[{"client_name":"majed10","addr":"Uttara"},{"client_name":"majed10","addr":"Uttara"}]
2
  • INNER JOIN's can return duplicated records indeed. Laraval's function distinct() should help you out here. Commented Dec 1, 2017 at 16:26
  • leftJoin('clients', function($join) { Commented Dec 1, 2017 at 16:26

1 Answer 1

8

Use distinct method:

$dsale=DB::table('directsales')
            ->join('clients','directsales.client_id','=','clients.id')
            ->select('clients.client_name','clients.addr')
            ->where('directsales.client_id','=',$client_id)
            ->distinct()
            ->get();

Ref: https://laravel.com/docs/5.5/queries#selects

Sign up to request clarification or add additional context in comments.

4 Comments

if, I want to add sum function in this query. how can i ??
You can add a raw query in it, but maybe it will not work with distinct. You can try with groupBy, it should fit the problem.
I appreciate this answer! The Laravel documentation inside the Database section has a single reference to distinct() in an example and no notes on it at all.
not working for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.