Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.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
Php 拉维关系法不起作用_Php_Laravel - Fatal编程技术网

Php 拉维关系法不起作用

Php 拉维关系法不起作用,php,laravel,Php,Laravel,花了几个小时解决这个问题后,我想请你帮忙 我的结构如下: 模型:Student.php class Student extends Model { protected $table = 'studenten'; public function kurs() { return $this->belongsTo(Kurs::class); } } 模型:Kurs.php class Kurs extends Model { protected

花了几个小时解决这个问题后,我想请你帮忙

我的结构如下:

模型:Student.php

class Student extends Model
{
    protected $table = 'studenten';

    public function kurs() {
        return $this->belongsTo(Kurs::class);
    }
}
模型:Kurs.php

class Kurs extends Model
{
    protected $table = 'kurse';

    public function studenten() {
        return $this->hasMany(Student::class);
    }
}
控制器:KursController.php

class KursController extends Controller
{
    public function showStudenten() {
        return view('example.studenten', [
            'kurse' => Kurs::all(),
        ]);
    }
}
查看:示例\studenten.blade.php

@foreach($kurse as $kurs)
    <p>{{ $kurs->title }}, {{ $kurs->id }}</p>
    @foreach($kurs->studenten() as $student)) 
      <p>{{ $student->name }}</p>
    @endforeach
@endforeach
表格:studenten

id | name | kurs_id | created_at | updated_at
我试图输出属于每门课程的学生。我的错误在哪里?我试图在我的模型方法中指定外键“kurs_id”,但它不起作用。 你能帮我找出我的错误吗

提前谢谢。

试试这个

在控制器中

 public function showStudenten() {
    return view('example.studenten', [
        'kurse' => Kurs::with('studenten')->get(),
    ]);
}
在您的视图文件中

@foreach($kurse as $kurs)
 <p>{{ $kurs->title }}, {{ $kurs->id }}</p>
   @foreach($kurs->studenten as $student)) 
    <p>{{ $student->name }}</p>
   @endforeach
@endforeach
@foreach($kurse作为$kurs)
{{$kurs->title},{{$kurs->id}

@foreach($kurs->studenten作为$student)) {{$student->name}

@endforeach @endforeach
您遇到了什么错误?我没有收到任何错误,但没有显示任何内容,尽管我以前尝试过“Kurse”,但没有效果,但现在它似乎起作用了。非常感谢你!你能解释一下为什么我这里不需要()吗?@Johannes-
studenten
是一个数组而不是一个函数它将返回数组的对象,在Laravel的雄辩函数中,你不需要使用()。它返回对象
@foreach($kurse as $kurs)
 <p>{{ $kurs->title }}, {{ $kurs->id }}</p>
   @foreach($kurs->studenten as $student)) 
    <p>{{ $student->name }}</p>
   @endforeach
@endforeach