2016-04-15 64 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

相關問題