繁体   English   中英

Laravel 表与数据透视表的关系

[英]Laravel table relationship to pivot table

我对如何使用连接到数据透视表的表在 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

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

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

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

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

有没有人有相同的用例?

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

谢谢

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

无需为数据透视表创建新模型。 只需在下面的代码中声明位置模型:

  /**
   * @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 表迁移。

如果这个答案解决了你的问题,请点击✔️并接受它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM