【问题标题】:Laravel questions about using One to One relationship between 2 tables关于在 2 个表之间使用一对一关系的 Laravel 问题
【发布时间】:2017-11-15 14:16:34
【问题描述】:

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

区表

区域模型

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

地址表

地址模型

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?
}

【问题讨论】:

  • 参考您提供的表格,District Model 中的方法address 应该返回hasMany 关系而不是hasOne。要获得 district 的名称,您应该使用 {{ $add->district->district_name }}

标签: php mysql laravel


【解决方案1】:

相反,您应该使用with 一次性获得所有价值

$getAddress = App\Address::with('district')->all();

并获得价值为

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

【讨论】:

  • 收到此错误...捕获 ErrorException: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$district_name
  • 试图获取我添加的非对象 id 的属性 [0]
  • brb 试试with
  • 在我修改了我的代码并使用了你的解决方案之后,它就可以工作了!太感谢了。使用with,只能调用模型函数吗?只是想扼杀我的好奇心:)
【解决方案2】:

你应该试试这个:

<php $getAddress = App\Address::with('district')->get(); ?>

@foreach($getAddress as $add)

   Address name: {{ $add->address_name }}

   @foreach($add->district as $districrt)
    District name : {{ $districrt->district_name }} 
  @endforeach

@endforeach

【讨论】:

    猜你喜欢
    • 2019-12-17
    • 2020-11-13
    • 2014-02-17
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 2019-11-25
    • 1970-01-01
    相关资源
    最近更新 更多