php - Laravel 关于在 2 个表之间使用一对一关系的问题

标签 php mysql laravel

我有2个,分别是districtaddress。假设这两个表之间存在关系。 address 表包含district 外键。问题是它在 View 中返回 null。如何显示/输出地区名称?我完全按照 Laravel 文档中的说明进行操作。

分区表

enter image description here

地区模型

public function address()
{
    return $this->hasOne('App\Address');
}

地址表

enter image description here

地址模型

public function district()
{
    return $this->belongsTo('App\District', 'district');
}

查看

$getAddress = App\Address::all();

foreach($getAddress as $add)
{
   Address name: {{ $add->address_name }}
   District name : {{ $add->district['district_name'] }} //this returns null, WHY?
}

最佳答案

相反,您应该使用 with

一次获得所有值
$getAddress = App\Address::with('district')->all();

并获取值(value)为

{{ $add->district->district_name }}

关于php - Laravel 关于在 2 个表之间使用一对一关系的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47300440/

相关文章:

php - 如何在除一个子页面之外的每个子页面上显示一些 html?

php - 我如何获得通过与 Laravel 5/Eloquent 的两个多对多关系关联的不同类别列表?

php - 如何安全地在虚拟主机上拥有多对多用户

php - 如何使用 PHP 转换规范化数据集?

mysql - SQL 查询不应返回数据透视表中包含空值的行

MySQL 查询为每个连接表行创建行

mysql - 如果条件列为真则添加值

php - 将新列添加到数据库表中,迁移失败并显示 - 无需迁移

php - 自动调整 Excel 列宽

php - 从 mysql 更改为 mysqli