Laravel 表与数据透视表的关系

Rob*_*iam 7 php laravel

我对如何使用连接到数据透视表的表在 laravel 中设置我的模型感到困惑。

问题来了

说我有

Locations
    id
    name

area_types
    id
    name

area_type_location (Pivot table)
    id
    location_id
    area_type_id

area_test
    id
    area_type_location_id
    clean
    headCount
Run Code Online (Sandbox Code Playgroud)

表之间的关系是不同的区域类型属于不同的位置。即:海滩、25m 游泳池、儿童游泳池、烧烤等

area_test 连接到数据透视表,因为测试必须从存在的区域生成,在这种情况下,它是在不同位置注册的区域。因此,必须每天对其进行测试、测量等。

我了解 area_types 和多对多关系位置之间的结构,但是我无法理解如何构建 area_test 模型?如何从位置表中获取数据 -> 我的测试在哪里?

我应该为我的数据透视表创建一个模型吗?这是laravel的好习惯吗?

有没有人有相同的用例?

我读到 eloquent有很多通过 关系,但我知道它没有提到通过数据透视表。我不太明白我的用例是否相同。

谢谢

Rob*_*iam 16

最后,显然有几种方法可以将数据从locations表中获取到area_tests

尝试了一下修补匠,它有效,


第一个选项

我需要为我的数据透视表创建一个数据透视模型:

class LocationAreaType extends Pivot{

    public function location(){
        return $this->belongsTo(Location::class);
    }

    public function areaType(){
        return $this->belongsTo(AreaType::class);
    }

    public function AreaTests(){
        return $this->hasMany(AreaTest::class, 'area_type_location_id');
    }

}
Run Code Online (Sandbox Code Playgroud)

我可以使用hasManyThrough需要在位置表中创建的关系

public function areaTests()
{
    return $this->hasManyThrough(
        AreaTest::class,
        LocationAreaType::class,
        'location_id',
        'area_type_location_id'
    );
}
Run Code Online (Sandbox Code Playgroud)

这样我就可以通过 轻松获得区域测试$location->areaTests,我的问题不是确定area_type_location_id为外国。您需要确定这一点,显然当我扩展枢纽并使用 hasMany laravel 时,它本身不会自动识别外键。


第二个选择

另一种访问它的方法是从关系表中,我可以withPivotareaTypes()关系中定义,然后像这样访问它:

$location->areaType[0]->pivot->areaTests

由于 laravel 只识别来自表location_id和的外键area_type_id,我必须包含id数据透视表的 来获取 AreaTest 表数据

所以在位置模型中我必须获取该列

public function areaTypes()
{
    // Get the ID of the pivot table to get the poolTests table (connected with ID column)
    return $this->belongsToMany(AreaType::class)
        ->using(AreaTypeLocation::class)
        ->withPivot('id');
}
Run Code Online (Sandbox Code Playgroud)