[英]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.我有一个名为 users 的表,用于存储用户信息,每个用户可以拥有多个存储在单独表中的企业帐户。
Models:楷模:
User:用户:
id ID
name名称
UserProviderAccount:用户提供者帐户:
id ID
user_id用户身份
bussiness_name公司名称
bussiness_tell商业诉说
bussiness_address公司地址
UserCompanyAccount用户公司帐户
id ID
user_id用户身份
company_name公司名
company_size公司规模
UserInfluencerAccount:用户影响者帐户:
id ID
user_id用户身份
name名称
website网站
follower_count 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用户控制器:示例 controller 和 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. users.show 视图:向您展示概念的简化版本。
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.