【问题标题】:Display Fields of Relationship Query in BladeBlade关系查询显示字段
【发布时间】:2017-09-30 10:23:34
【问题描述】:

在模型中绑定表并编写查询后,在 Blade 中获取数据显示错误。

试图获取非对象的属性

型号

<?php

public function unit()
{
    return $this->belongsTo('TEST\Units');
}

查询

$inst = Instructions::with('unit')
     ->where('id',$inst_id)
     ->first()
     ->get();

型号

@foreach ($inst as $item)
    <pre>{{$item->units->name}}</pre>
@endforeach

但是,当使用此代码并删除名称或其他字段时,不会显示错误...

@foreach ($inst as $item)
    <pre>{{$item->units}}</pre>
@endforeach

输出:

{"id":1,"name":"UNIT 101","description":null,"created_at":"2017-03-06 13:30:18","updated_at":"2017-03-06 13:30:18"}

【问题讨论】:

  • 您不必在first 之后调用getfirst 内部调用 get 方法。
  • 我不知道你到底想达到什么,但你得到 1 个结果(使用first())然后遍历它?
  • 我想在我的视图中显示获取的数据。使用此语法时,没有错误
    {{$item->units}}
    但是将字段添加到 $item->units->MYFIELD 发生错误。我不能使用字段名称 MYFIELD
  • 你必须将你的方法重命名为units而不是unit

标签: laravel laravel-5 relationship laravel-blade


【解决方案1】:

解决了

            @foreach ($inst as $item)
                @if (!empty($item->unit->id))
                <pre>{{$item->unit->name}}</pre>
            @endif
        @endforeach

【讨论】:

    猜你喜欢
    • 2019-01-23
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多