0

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.

3
  • do u use eloquent? Commented Feb 19, 2018 at 12:07
  • $clientdata = DB::table('clients')->get(); Commented Feb 19, 2018 at 12:17
  • this type of query i am using Commented Feb 19, 2018 at 12:18

2 Answers 2

1

Try this:

DB::Table('clients')
->leftjoin('relations', 'relations.id', '=', 'clients.relation_id')
->select('clients.*', 'relations.title')
->get();
Sign up to request clarification or add additional context in comments.

Comments

0

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

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??
can i have tables names ?
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
$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.
Thats laravel syntax anyways, what error are you getting ?
|

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.