简体   繁体   中英

How to get information from 3 separate tables in Laravel

I have a table called users that stores user information and each user can have multiple business accounts that are stored in separate tables.

Models:

User:

id

name

UserProviderAccount:

id

user_id

bussiness_name

bussiness_tell

bussiness_address

UserCompanyAccount

id

user_id

company_name

company_size

UserInfluencerAccount:

id

user_id

name

website

follower_count

Tables Relations:

User:

    public function providers(): HasMany
    {
        return $this->hasMany(UserProviderAccount::class);
    }
    public function companies(): HasMany
    {
        return $this->hasMany(UserCompanyAccount::class);
    }
    public function influencers(): HasMany
    {
        return $this->hasMany(UserInfluencerAccount::class);
    }

I want to display the user's business accounts of all three types at once.

How do I do this?

You simply need to load and call the relationships as follows:

UserController: sample controller and function

public function show(User $user){
    //Here we will load all of the relationships for the specific user
    $user->load('providers', 'companies', 'influencers');

    //Assign the providers from user->providers
    $providers = $user->providers;
    
    //Assign the companies from user->companies
    $companies = $user->companies;
    
    //Assign the influencers from user->influencers
    $influencers = $user->influencers;

    //Send all of the data to the view
    return view('users.show', compact('user', 'providers', 'companies', 'influencers'));
}

users.show View: simplified version to show you concept.

<p>{{$user->name}}</p>

<p>The providers:</p>
<ul>
    @foreach($providers as $provider)
        <li>{{$provider->bussiness_name}}</li>
        <li>{{$provider->bussiness_tell}}</li>
        <li>{{$provider->bussiness_address}}</li>       
    @endforeach
</ul>

<p>The companies:</p>
<ul>
    @foreach($companies as $company)
        <li>{{$company->company_name}}</li>
        <li>{{$company->company_size}}</li>     
    @endforeach
</ul>

<p>The influencers:</p>
<ul>
    @foreach($influencers as $influencer)
        <li>{{$influencer->name}}</li>
        <li>{{$influencer->website}}</li>
        <li>{{$influencer->follower_count}}</li>        
    @endforeach
</ul>

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