试图获取非对象的属性“名称”?

问题描述 投票:-1回答:4

嗨,我是laravel的新手,我正在尝试检索每种编队的类别名称,并且出现此错误

试图获取非对象(0)的属性'名称'

我试图检索的“名称”是我的阵营所属的类别的名称。

这是我的分类模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    function formations()
        {
            return $this->hasMany('App\Formation');
        }

    protected $fillable =['name','description'];
}

这是我的编队模型

class Formation extends Model
{
   function category()
       {
           return $this->belongsTo('App\Category',"category_id");
       }
   protected $fillable =['name','price','durations','category_id'];
}

这是我的视图页面,我正在其中尝试检索类别名称

@foreach($formations as $formation)

        <td>{{$formation->name}}</td>
        <td>{{$formation->price}}</td>
        <td>{{$formation->category->name}}</td>
        td>{{$formation->durations}}</td>

@endforeach

这是我的控制器

    public function index()
{
    //$formations = Formation::all();
    $formations = Formation::with('category')->paginate('4');
    $categories = Category::all();
    return view('formation.index',compact('categories','formations'));
}

关于我可能在哪里的任何建议?在此先感谢!

laravel
4个回答
0
投票

当您从数据库中删除了一个或多个行,但尝试使用id访问该行时,通常会发生此错误。确保category表中的所有类别都包含idformation字段中提到的category_id


0
投票

您认为

@foreach($formations as $formation)
 <td>{{$formation->name}}</td>
 <td>{{$formation->price}}</td>
 <td> {{ $formation->categories()->pluck('name')->implode(' ') }}</td>
 <td>{{$formation->durations}}</td>
@endforeach

0
投票

尝试更改关系

class Formation extends Model
{
function category()
   {
       return $this->belongsTo('App\Category',"id","category_id"); //if your categories id is id
   }
protected $fillable =['name','price','durations','category_id'];
}

您认为

  @foreach($formations as $formation)

    <td>{{$formation->name}}</td>
    <td>{{$formation->price}}</td>
    <td>{{$formation->category->name}}</td>
    <td>{{$formation->durations}}</td>

  @endforeach

0
投票

问题是我从数据库的类别表中删除了一行,这就是为什么无法识别该名称的原因。

© www.soinside.com 2019 - 2024. All rights reserved.