i have two tables first is clients and second one is relations. in relations table i have two fields namely id and title. my clients table contain field relation_id which is related to relations table id. Now my question is that how can i fetch clients table data but instead of relation_id i want corresponding title which is in relations table in laravel.
-
do u use eloquent?Adam Kozlowski– Adam Kozlowski2018-02-19 12:07:55 +00:00Commented Feb 19, 2018 at 12:07
-
$clientdata = DB::table('clients')->get();Ram Agrawal– Ram Agrawal2018-02-19 12:17:41 +00:00Commented Feb 19, 2018 at 12:17
-
this type of query i am usingRam Agrawal– Ram Agrawal2018-02-19 12:18:07 +00:00Commented Feb 19, 2018 at 12:18
Add a comment
|
2 Answers
Well if you already setup relations in your model you can simply use Eager Loading like this:
Client::with('your relation')->get();
or you can use Join
Client::leftJoin('table1', 'table2')->select('select columns that you want')->get();
leftJoin is a little bit hard if you have no clue what is join/leftJoin/RightJoin or innerjoin
Here is another example from laravel doc which is more suitable for your case
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
Edit: Based on what you provided here your query should be something like this:
$clientdata = DB::table('clients')->leftJoin('clients.id', '=' ,'relations.relation_id')->select('clients.*', 'relations.id as rel_id', 'relations.relation-title')->get();
7 Comments
Ram Agrawal
in clients table i have three fields namely name, mobile and relation_id . relation_id is related to id of relations table, now i want to get all clients table information but instead of relation_id i want title from relations table, so please can you explain me it with code??
AH.Pooladvand
can i have tables names ?
Ram Agrawal
two tables first is clients in which fields are name, mobile, and relation_id, and second table relations in which field id and relation-title
Ram Agrawal
$clientdata = DB::table('clients')->leftJoin('clients.id', '=' ,'relations.relation_id')->select('clients.*', 'relations.id as rel_id', 'relations.relation-title')->get(); this is not working in laravel.
AH.Pooladvand
Thats laravel syntax anyways, what error are you getting ?
|