【问题标题】:How to fetch data from database if one model has relation with two models in Laravel如果一个模型与 Laravel 中的两个模型有关系,如何从数据库中获取数据
【发布时间】:2021-07-17 04:04:15
【问题描述】:

我正在尝试使用 Laravel eloquent 从数据库中获取数据,但它没有返回任何数据。这是数据库结构

  • 地区

    • 身份证
    • 姓名
    • 身份证
    • 姓名
    • region_id
  • 病房

    • 身份证
    • 姓名
    • region_id

因此,病房与地区无关,而与地区有关。我怎样才能获得病房(数据)?这就是我获取数据的方式

Area::with('region.district.ward')->get();

型号

Region.php

public function district()
    {
        return $this->hasMany(District::class);
    }

public function ward()
   {
    return $this->hasMany(Ward::class);
   }

区.php

public function region()
    {
        return $this->belongsTo(Region::class);
    }

Ward.php

public function regions()
    {
        return $this->belongsTo(Region::class);
    }

【问题讨论】:

  • 可能你想要Region::with('district')->with('ward')->get();这样的东西
  • 如果我使用它,如果我有Area::with('region.district.ward')->get(); 我如何获得ward? @EsTeAa
  • 这样Area::with('region.ward')->get();或者一起Area::with(['region.district','region.ward'])->get();

标签: laravel laravel-5 eloquent


【解决方案1】:

当您有类似链接结构的数据时,您可以使用 dot 表示法预先加载后代表,例如 table2 => table2 => table 3

Model1::with('model2.model3')->get();

但是你的数据不是链式结构,所以你可以通过:

Region::with('district')->with('ward')->get();

或者,

Region::with(['district', 'ward'])->get();

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2020-10-11
    • 2016-03-09
    • 2018-12-29
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多