2016-04-15 13 views
0

2つのモデルがあります。 1.コース。 2.手数料。Laravel 5.2:1対1の雄弁(hasOne)関係からデータを取り出す方法

1つのコースには1つの料金があります。入力をしている間は完全にOKですが、料金データにアクセスしようとすると、料金の列に何も表示されません。どうすれば解決できますか?

コースモデル:

<?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 FeeCourseを意味に注意してくださいをする必要がありますので、関係がFeeに向けてCourse側から開始する必要があります。

あなたのコースモデル

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

関連する問題