2016-04-15 62 views
0

我有两个模型: 1.课程。 2.费用。Laravel 5.2:如何从一对一的口头获取数据(hasOne)关系

一门课程只有一个费用。在给出输入时,它完全没问题,但当我试图访问费用数据时,它没有显示任何费用列。我如何解决它?

课程模式:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Course extends Model 
{ 
    protected $table='courses'; 
    protected $fillable = ['name']; 


    public function fee(){ 
     return $this->belongsTo('App\Fee'); 
    } 

} 

费计算模型:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Fee extends Model 
{ 
     protected $table='fees'; 
    protected $fillable = ['fee','course_id']; 
    public function course() 
    { 
     return $this->hasOne('App\Course'); 
    } 
} 

控制器:

​​

查看页:

<html> 
    <head> 
     <title> Course Details </title> 

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> 

    </head> 
    <body> 


<div class="container"> 
<h3> Student Details </h3> 
     <table class="table table-striped table-bordered" id="example"> 
     <thead> 
      <tr> 
      <td>Serial No</td> 
      <td>Course Name</td> 
      <td>Course Fee</td> 


     </tr> 
     </thead> 
     <tbody> 
      <?php $i=1; ?> 
     @foreach($course as $row) 

      <tr> 
      <td>{{$i}}</td> 
      <td>{{$row->name }}</td> 

      <td> @if($row->course) 
        {{$row->course->fee}} 
        @endif</td> 


      </tr> 
      <?php $i++; ?> 

     @endforeach 
     </tbody> 


     </table> 

    </div> 

    </body> 
</html> 
+0

我不完全确定我了解您的情况。它看起来像你正在调用'课程'的方法 – tam5

+0

我想使用课程表访问费用表数据,其中id与course_id匹配。 – User57

回答

3

你似乎错误地写下了关系......就这样做。

记住,Course Has The Fee意味着Course是必须的,所以关系应该从Course侧向Fee开始。

你的课程模式

class Course extends Model 
{ 
    protected $table='courses'; 
    protected $fillable = ['name']; 


    public function fee(){ 
     return $this->hasOne('App\Fee','course_id', 'id'); 
    } 

} 

你的收费模式

class Fee extends Model 
{ 
    protected $table='fees'; 
    protected $fillable = ['fee','course_id']; 
    public function course() 
    { 
     return $this->belongsTO('App\Course', 'course_id', 'id'); 
    } 
} 

现在你可以这样做,得到的关系。

public function listofCourse(){ 
     $course=\App\Course::with('fee')->get(); 
     // doing this for dumping purpose 
     echo "<pre>"; 
     print_r($course->toArray()); // you will see the `fee` array 
     echo "</pre>"; 
     die(); 
     return view('listofCourse',compact('course')); 
} 
+0

谢谢兄弟! 解决了它! – User57

相关问题