[英]Laravel 5.4 - multiple relations in few tables
In a picture below we can see relations between my tables. 在下面的图片中,我们可以看到我的表之间的关系。 My target is to get " type " from driver_license_types . 我的目标是从driver_license_types获取“ 类型 ”。 Starting at user object. 从用户对象开始。 For example: 例如:
$user = User::find(1);
and from there I need to get type from driver_license_types. 从那里我需要从driver_license_types获取类型。 Important thing is that instructors can have few records in instructor_license_types table, like this: 重要的是,讲师在讲师_许可证_类型表中几乎没有记录,如下所示:
My current solutions: 我当前的解决方案:
And final code look like: 最终代码如下所示:
Is there any better solutions? 有没有更好的解决方案?
You can get the driver_license_types directly from the Instructors model by adding this function: 您可以通过添加以下函数直接从Instructors模型中获取driver_license_types:
//PathToModel\Instructor.php
public function license_types()
{
return $this->belongsToMany('PathToModel\LicenseTypes', 'instructors_license_types');
}
Also add this to the LicenseType model: 还将其添加到LicenseType模型:
//PathToModel\LicenseTypes.php
public function instructors()
{
return $this->belongsToMany('PathToModel\Instructors', 'instructors_license_types');
}
This way you will be able to remove one of your foreach statements in your code: 这样,您将能够在代码中删除其中一个foreach语句:
$user = User::find($id);
if($user->instructor){
$tmp = [];
foreach ($user->instructor->license_types as $data) {
array_push($tmp, [$data->id, $data->type]);
}
$user->types = $tmp;
}
What this does is just skips over the pivot table (instructos_license_types), for more info on this you can see docs here . 这样做是刚刚跳过数据透视表(instructos_license_types),更多信息在此你可以看到文档在这里 。
If you don't have belongsToMany
relationship set up in your Instructor
model for DriverLicenseType
I would suggest putting one in: 如果您在Instructor
模型中没有为DriverLicenseType
设置belongsToMany
关系,我建议您输入以下内容:
public function licenseTypes()
{
return $this->belongsToMany(DriverLicenseType::class, 'instructors_license_types', 'instructor_id', 'driver_license_type_id');
}
$user = User::find(1);
$licenseTypes = $user->instructor->licenseTypes->pluck('type')->unique();
or if you need the $licenseTypes
to be in the format you have in your question you could do something like: 或者,如果您需要将$licenseTypes
设置为问题格式,则可以执行以下操作:
$licenseTypes = $user->instructor->licenseTypes->map(function ($item) {
return [$item->id, $item->type];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.