Pankaj Agrawal
Pankaj Agrawal

Reputation: 1659

implement joins with laravel 5

I am trying to implement following join query

SELECT * from users as u

LEFT JOIN `table1` as ou

ON ou.user_id = u.id

LEFT JOIN table2 as o

ON o.id = ou.orid

LEFT JOIN table3 as p

ON o.pra_id = p.id;

with my laravel model so i create a function named alldata() in my user model with following code

public function alldata()

{

    return $this

        ->leftjoin('table1','users.id','=','table1.user_id')

        ->leftjoin('table2','table1.orid','=','table2.id')

        ->leftjoin('table3','table2.pra_id','=','table3.id');

}

now when i try to access the data by $gd = User::find(1)->getall() it returns results with all the table but when i try to acces $gd = User::all()->alldata() it gaves error mathod not found how can i resolve this thanks

Upvotes: 2

Views: 51

Answers (1)

RCrowt
RCrowt

Reputation: 961

The User::find(1) function returns an single instance of the object (or NULL if not found).

The User::all() function returns a Collection of all User objects.

You need to create a query then get() the results as follows...

public static function alldata()
    {

    return self::query()
        ->leftjoin('table1','users.id','=','table1.user_id')
        ->leftjoin('table2','table1.orid','=','table2.id')
        ->leftjoin('table3','table2.pra_id','=','table3.id')
        ->get();
}

Assuming your your alldata() method is in the User class you can call the function with the following code:

User::alldata();

Laravel has a excellent database relationship system which is most defiantly worth looking at. It would make queries like the one above much simpler...

https://laravel.com/docs/5.1/eloquent-relationships

Upvotes: 1

Related Questions