在 Laravel 多对多关系中编写更好的代码
嗨,我写了这段代码,它工作得很好,但我认为这不是最好的方法!
我想获得一家公司的所有职位。
每个公司可以有很多地址,每个地址可以有很多工作
这是我的代码:
$company = Company::find($id)->with('addresses.jobDetails.job')->first();
$jobs = [];
foreach ($company->addresses as $address) {
foreach ($address->jobDetails as $detail) {
array_push($jobs, [
'id' => $detail->job->id,
'title' => $detail->job->title,
'country' => $detail->job->country,
'city' => $detail->job->city,
'type' => $detail->job->type,
'work_types' => JobType::where('job_id',$detail->job->id)->pluck('title'),
'income' => $detail->income,
]);
}
}
return $jobs;
任何人都可以帮助我将其更改为更好的代码,请
提前感谢您
hi i wrote this code and it works just fine but i think its not the best way to do it!
i want to get all the jobs for 1 company.
each company can have many addresses and each address can have many jobs
here is my code:
$company = Company::find($id)->with('addresses.jobDetails.job')->first();
$jobs = [];
foreach ($company->addresses as $address) {
foreach ($address->jobDetails as $detail) {
array_push($jobs, [
'id' => $detail->job->id,
'title' => $detail->job->title,
'country' => $detail->job->country,
'city' => $detail->job->city,
'type' => $detail->job->type,
'work_types' => JobType::where('job_id',$detail->job->id)->pluck('title'),
'income' => $detail->income,
]);
}
}
return $jobs;
can anyone help me to change this to better code please
thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您执行相反的操作,并从 JobDetails
编辑:
在查询中
开始,您通过预加载运行 4 个查询。每个型号一个。您可以检查得到的结果,所有数据都存在于变量
$company
中。我给您提供的示例仅运行两个查询,第一个查询 (job_details) 将使用联接通过 Companies 表的
id
过滤作业结果(您可以通过使用字段 < 使其更快)地址表中的 code>company_id)第二个是使用预先加载的工作关系。
You do the opposite and start with JobDetails
EDIT:
In your query
You run 4 queries with eager loading. one for each model. You can check in the result that you got that all the data is present in the variable
$company
.The example I gave you it runs only two queries, the first one (job_details) will use joins to filter the Job results by the
id
of the companies table (you can make it faster by using the fieldcompany_id
in the addresses table)The second one is for the jobs relation using eager loading.