Home (Laravel / Eloquent) How to join 4 tables to make 1 query
Reply: 1

(Laravel / Eloquent) How to join 4 tables to make 1 query

Carlos
1#
Carlos Published in 2015-06-01 20:00:16Z

I'm new at Laravel and I want some help with a Query. Here is my situation. I have 4 tables:

  • users (id, email, password.....)
  • user_profile (id, first_name, last_name,........, user_id)
  • companies (id, name,.......)
  • policies (id, policy_num, exp_date,........., user_id, company_id)

The table user have 5 users and every user have 10 policies. The table company have 3 companies.

$user_data=User::select('*')
                ->with('profile','policies')
                ->where('id', '=', $userId)
                ->first();

This code is working good, it retrieves the all the users and user_profile fields and all the policies(10) of this user with as you can see in this image, and I can show the user the details of the products on a home page.

I want to instead of appear the company_id from the policies table appears the name of the company from the company table. Any help is appreciated.

Carlos
2#
Carlos Reply to 2015-06-01 20:05:51Z

Thank you for your answer ceejayoz, i already did.

User

public function profile()
    {
        return $this->hasOne('UserProfile');
    }

public function policies()
    {
        return $this->hasMany('Policy');
    }

Policy

public function company()
    {
        return $this->hasOne('Company');
    }
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301163 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO