Laravel表与数据透视表关系

uinbv5nw  于 2022-11-18  发布在  其他
关注(0)|答案(2)|浏览(158)

我对如何在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

表之间的关系是不同的区域类型属于不同的位置。即:海滩、25米泳池、儿童泳池、烧烤等
area_test连接到数据透视表,因为测试必须从存在的区域生成,在这种情况下,它是在不同位置注册的区域。因此,它必须每天测试,测量等。
我理解area_types和locations之间的多对多关系,但是我不知道如何构建我的area_test模型?我如何从locations表中获取数据-〉我的测试在哪里?
我应该为我的数据透视表创建一个模型吗?这在laravel中是一个好的做法吗?
是否有人拥有相同的使用情形?
我读到了关于proficent有很多直通关系,但我知道它没有提到直通数据透视表。我不太明白我的用例是否相同。
谢谢

jdgnovmf

jdgnovmf1#

最后,显然有两种方法可以将数据从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');
}

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

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

这样我就可以通过$location->areaTests很容易地得到areaTests,我的问题是没有确定area_type_location_id为外键。你需要确定这一点,显然当我扩展pivot并使用hasMany时,laravel本身不会自动识别外键。

第二个选项

另一种访问它的方法是从关系表中,我可以在areaTypes()关系中定义withPivot,然后按如下方式访问它:
$location->areaType[0]->pivot->areaTests
由于laravel仅识别表location_idarea_type_id中的外键,因此我必须包含透视表的id以获取AreaTest表数据
所以在Location模型中我必须得到列

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');
}
cetgtptt

cetgtptt2#

透视表不需要新建模型,只需在Location模型中声明如下代码即可:

/**
   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
   */
  public function area_types()
  {
        return $this->belongsToMany('App\AreaType', 'area_type_location', 'location_id', 'area_type_id');

  }

并在AreaType模型中声明以下代码:

/**
   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
   */
  public function locations()
  {
        return $this->belongsToMany('App\Location', 'area_type_location', 'area_type_id', 'location_id');

  }

每当你需要获取每个控制器中area_type的位置时,你可以像这样调用函数:$areatype->locations()->get();
不要忘记创建area_type_location表迁移。

相关问题