Warm tip: This article is reproduced from stackoverflow.com, please click
database laravel php

How to get data from another table from database?

发布于 2020-03-27 10:19:01

I want to get data from table role_users , column role_id . For the moment, I have this in my controller :

$data['contact_users'] = DB::table('contacts')
                    ->join('users' , 'users.id', '=', 'contacts.contact_id')
                    ->join('industries' , 'industries.id', '=', 'users.industry_id')
                    ->join('countries' , 'countries.id', '=', 'users.country_id')
                    ->join('organization_types' , 'organization_types.id', '=', 'users.organization_type_id')
                    ->select('users.*','industries.industry','countries.country','organization_types.organization_type')
                    ->where('contacts.contact_id','!=',$id)
                    ->where('users.deleted_at','=',NULL)
                    ->whereIn('contacts.user_id', $contact_id)
                    ->whereNotIn('contacts.contact_id', $contact_id)
                    ->whereNotIn('contacts.contact_id', $inviter_id)
                    ->groupBy('contact_id')
                    ->take(4)
                    ->get();

I'm using it in view with this code :

{{$contact->industry_id}} or {{$contact->country_id}}

I need to use something like this.

{{$contact->role_id}}

which is working for every user.But I need to get data from role_users,column role_id.I don't know how to use ->join() and I need it so much.Thank you.

Questioner
Andrei Nagy
Viewed
115
243 2019-07-04 14:15

I added one extra join and one select field at the end,

$data['contact_users'] = DB::table('contacts')
    ->join('users', 'users.id', '=', 'contacts.contact_id')
    ->join('industries', 'industries.id', '=', 'users.industry_id')
    ->join('countries', 'countries.id', '=', 'users.country_id')
    ->join('organization_types', 'organization_types.id', '=', 'users.organization_type_id')
    ->join("role_users", "role_users.user_id","=","users.id")
    ->select('users.*', 'industries.industry', 'countries.country', 'organization_types.organization_type', "role_users.role_id")
    ->where('contacts.contact_id', '!=', $id)
    ->where('users.deleted_at', '=', null)
    ->whereIn('contacts.user_id', $contact_id)
    ->whereNotIn('contacts.contact_id', $contact_id)
    ->whereNotIn('contacts.contact_id', $inviter_id)
    ->groupBy('contact_id')
    ->take(4)
    ->get();