尝试获取 属性 共 non-object Laravel 5,4

Trying to get property of non-object Laravel 5,4

我是 Laravel 的新人。我只想问我的代码是否正确。我想在 Collection 文件夹中的 index.blade.php 中的某个作业中显示该区域的楼层和建筑物的名称。 Collections属于一个Assignment,而Assignments属于一个Area。

我的代码在Collectionindex.blade.php

@foreach ($collections as $collection)
  <tr>    
     <td>
         {{ $collection->assignment->area['floor'] }} Floor
         {{ $collection->assignment->area['building'] }}
     </td> 
  <tr>
@endforeach

该代码生成错误 "Trying to get property of non-object"。所以我问的是正确的显示方式。

这是模型

Collection.php

public function assignment()
{
    return $this->belongsTo(Assignment::class);
}

Assignment.php

public function collections()
{
    return $this->hasMany(Collection::class);
}
public function area()
{
    return $this->belongsTo(Area::class);
}

Area.php

public function assignments()
{
    return $this->hasMany(Assignment::class);
}

CollectionsController.php

public function index() //shows the table of the collections
{
    $collections = Collection::all();
    $disposals = Disposal::all();
    return view('collections.index', compact('collections', 'disposals'));
}

你应该使用这样的区域

$collection->assignment()->area()->building

以下几乎任何部分都完全有可能 returning a null:

$collection->assignment->area

如果此特定集合不存在从集合到赋值的关系,则将为它创建 null returned。 这将适用于所有 singular 关系。

您将需要检查这些,弄清楚如何 return 在 null 的情况下进行一些默认设置,或者保证关系始终存在于数据库中。

可能是因为所有记录都没有将数据连接到子表中,否则错误会增加。要克服错误,您可以使用 optional() 方法。

方法将自动处理空关系。

optional($collection->assignment)->area

更多信息你可以查看这个link 祝你好运

"UPDATE": The problem is from the unclosed tr tag you opened it <tr><tr> like this but it should be <tr></tr> :D that's it, check the solution and tell me if it works. but look at the bright side, your code is cleaner and more pragmatic now :D

链接不好 :),尝试创建一个函数来获取区域,否则...

或者您可以使用 withDefault 和 return 相关模型的新实例

此外,您的数据库方案应如下所示:

合集

  • id
  • assignment_id

作业

  • 编号
  • area_id

laravel withDefault doc

但是对于你的例子我可以这样做:

Collection.php

public function assignment()
{
    return $this->belongsTo(Assignment::class)
        ->withDefault();
}

Assignment.php

public function collections()
{
    return $this->hasMany(Collection::class);
}
public function area()
{
    return $this->belongsTo(Area::class)
        ->withDefault();
}

Area.php

public function assignments()
{
    return $this->hasMany(Assignment::class);
}

CollectionsController.php

public function index() //shows the table of the collections
{
    $collections = Collection::all();
    $disposals = Disposal::all();
    return view('collections.index', compact('collections', 'disposals'));
}

也适用于:

@foreach ($collections as $collection)
  <tr>    
     <td>
         {{ $collection->assignment->area->floor }} Floor
         {{ $collection->assignment->area->building }}
     </td> 
  <tr/>
@endforeach

如果一切正常,仍然没有结果,请检查数据本身是否存在,因此检查是否有任何集合的分配,或分配的任何区域returned.. .