douhuanglou1445 2016-09-27 21:23
浏览 19
已采纳

Laravel关系方法不起作用

after spending hours on solving this issue I want to ask you for help.

I have the following structure:

Model: Student.php

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

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

Model: Kurs.php

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

    public function studenten() {
        return $this->hasMany(Student::class);
    }
}

Controller: KursController.php

class KursController extends Controller
{
    public function showStudenten() {
        return view('example.studenten', [
            'kurse' => Kurs::all(),
        ]);
    }
}

View: example\studenten.blade.php

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

Table: kurse

id | title | created_at | updated at

Table: studenten

id | name | kurs_id | created_at | updated_at

I'm trying to output the students belonging to every course. Where is my error? I tried to specify the foreign key 'kurs_id' in my model methods but it won't work. Could you please help me to find my mistake?

Thank you in advance.

  • 写回答

1条回答 默认 最新

  • douqin7086 2016-09-27 21:30
    关注

    Try this

    In Your Controller

     public function showStudenten() {
        return view('example.studenten', [
            'kurse' => Kurs::with('studenten')->get(),
        ]);
    }
    

    In your view file

    @foreach($kurse as $kurs)
     <p>{{ $kurs->title }}, {{ $kurs->id }}</p>
       @foreach($kurs->studenten as $student)) 
        <p>{{ $student->name }}</p>
       @endforeach
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan