Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 5 Laravel-hasMany()和belongsTo()在@foreach循环中对我不起作用_Laravel 5_Eloquent - Fatal编程技术网

Laravel 5 Laravel-hasMany()和belongsTo()在@foreach循环中对我不起作用

Laravel 5 Laravel-hasMany()和belongsTo()在@foreach循环中对我不起作用,laravel-5,eloquent,Laravel 5,Eloquent,当我尝试在我的页面上使用此选项时,出现以下错误 正在尝试获取非对象的属性 我有两张桌子: cvicenis id title body category_id categories id name 我的Cviceni模型: namespace App; use Illuminate\Database\Eloquent\Model; class Cviceni extends Model { public function category()

当我尝试在我的页面上使用此选项时,出现以下错误

正在尝试获取非对象的属性

我有两张桌子:

cvicenis
  id
  title
  body
  category_id
categories
  id
  name
我的Cviceni模型:

namespace App;    
use Illuminate\Database\Eloquent\Model;

class Cviceni extends Model
{
    public function category() 
    {
        return $this->belongsTo('App\Category', 'id');
    }
}
我的类别模型:

namespace App;    
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function cviceni()
    {
        return $this->hasMany('App\Cviceni', 'category_id');
    }
}
我的控制器:

public function index()
{
    $cviceni = Cviceni::all();
    return view('excercises.index', compact('cviceni'));
}

我的index.blade:

@extends('layouts.app')

@section('content')
    <div class="row">
        <div class="col-sm-6 col-md-6 col-lg-3">
            <h1>Přehled cvičení</h1>
            @if(count($cviceni) > 0)
            <ul>
                @foreach ($cviceni as $c)
                    <li> {{ $c->category->name }}</li>
                @endforeach
            </ul>
            @else
                <h2>There is nothing to display</h2>
            @endif
        </div><!-- end of column -->
    </div><!-- end of row -->
@endsection
@extends('layouts.app'))
@节(“内容”)
Přehled cvičení
@如果(计数($cviceni)>0)
    @foreach($cviceni作为$c)
  • {{$c->category->name}
  • @endforeach
@否则 没有什么可展示的 @恩迪夫 @端部
如果我在我的控制器中使用
Cviceni::find(1)
,那么我可以从$Cviceni->category->name中获取值 但当我使用
foreach
循环时,情况就不是这样了。
有人能帮我吗?

如果需要,您需要加载模型:

public function index()
{
    $cviceni = Cviceni::with("category")->get();
    return view('excercises.index', compact('cviceni'));
}

在Cviceni模型中,我认为您设置的外键是错误的。表中的外键为category_id,而设置外键为id的关系。请尝试用follow替换category()关系

public function category() 
{
    return $this->belongsTo('App\Category', 'category_id');
}
这没有帮助:(当我尝试通过foreach循环运行它时,仍然会出现相同的错误…即使我尝试了类似
$cviceni[0]->category->name