简体   繁体   中英

Laravel, three table relationship on Eloquent

I really need help with this big issues I have. I have tree table:

companies:

id  |  owner_id |  name   |   address
-------------------------------------
1   |    5      |  Google |  25 St RD
2   |    5      |  Yahoo  |  36 Ave St
3   |    11     |Microsoft|  1 Ave St
4   |    5      | Amazon  |  25 St NE

users:

id  |   name    |  email  |   type
-------------------------------------
3   |  Daniel   |  dn@gmail.com  |  customers
4   |    Dave   |  vd@gmail.com  |  user
5   |    Nancy  |  ncn@gmail.com |  admin
6   |  Robert   |  rb@gmail.com  |  user

user_companies

id  |  user_id  |parent_id| company_id
-------------------------------------
1   |    3      |  5      |     2
2   |    3      |  5      |     2
3   |    11     |  5      |     3
4   |    3      |  6      |     1

Issue one : I need to return all users that have been associated with company_id 2 This is the code I have but it's not returning correct data.

$CompanyList = DB::table('users')
            ->leftJoin('user_companies', 'users.id', '=', 'user_companies.parent_id')
            ->join('companies', 'users.id', '=', 'companies.user_id')->where('company_id', '=', 5)
            ->get(['users.name', 'users.email', 'user_companies.user_id']);

Note: parent_id is the id of who created the company record. I use it somewhere else.

Issue two : I have the user_id 5 and I need to return all companies associated with user_id 5. I was trying to with same code but wasn't successful.

Any help will be appreciated.

First of all you are not using the Eloquent Relations of Laravel, this is just old school MySQL Relations.

Second i do not understand your parent_id in the user_companies. If a company has a parent you wil set it in the company table as column not in the relation table.

And your relation table "user_companies" is has no unique keys so you have the first two result with the same result.

Make sure your normalisation is OK before you create de database tables, then read the for example the doc of Laravel: https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM