为了账号安全,请及时绑定邮箱和手机立即绑定

拉拉维尔表与数据透视表的关系

拉拉维尔表与数据透视表的关系

PHP
繁星点点滴滴 2022-09-25 20:31:32
我对如何使用连接到数据透视表的表在laravel中获取模型设置感到困惑。这是问题所在假设我有Locations    id    namearea_types    id    namearea_type_location (Pivot table)    id    location_id    area_type_idarea_test    id    area_type_location_id    clean    headCount表之间的关系是不同的区域类型属于不同的位置。即:海滩,25米游泳池,儿童游泳池,烧烤等area_test连接到数据透视表,因为测试必须从存在的区域生成,在这种情况下,它是在不同位置下注册的区域。因此,它必须每天进行测试,测量等。我了解area_types和位置之间的结构,但是我无法克服如何构建我的area_test模型?如何从位置表中获取数据 >我的测试在哪里?我应该为数据透视表创建模型吗?这在拉拉维尔是一个好习惯吗?有没有人有相同的用例?我读到关于雄辩有很多通过关系,但我明白它没有提到通过数据透视表。我不太明白我的用例是否相同。谢谢
查看完整描述

2 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

最后,显然有几种方法可以将数据从表格中获取locationsarea_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');

}

}


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


public function areaTests()

{

    return $this->hasManyThrough(

        AreaTest::class,

        LocationAreaType::class,

        'location_id',

        'area_type_location_id');

}

这样我就可以很容易地得到这个地区测试,我的问题是不是确定为外国的。你需要确定这一点,显然当我扩展枢轴和使用有许多拉拉维尔不会自动识别外键本身。$location->areaTestsarea_type_location_id


第二种选择

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


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


由于拉拉维尔只识别两个表和的外键,我必须包括数据透视表才能获得 AreaTest 表数据location_idarea_type_idid


因此,在位置模型中,我必须获取列


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

}


查看完整回答
反对 回复 2022-09-25
?
FFIVE

TA贡献1797条经验 获得超6个赞

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


  /**

   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany

   */

  public function area_types()

  {

        return $this->belongsToMany('App\AreaType', 'area_type_location', 'location_id', 'area_type_id');


  }

并在区域类型模型中声明以下代码:


  /**

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


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


查看完整回答
反对 回复 2022-09-25
  • 2 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信