[英]Laravel 5.2 : How to retrieve data from one to one eloquent (hasOne) Relationship
I have two Models: 1. Course. 我有两个模型:1.课程。 2. Fee.
2.费用。
One course has only one fee. 一门课程仅需支付一项费用。 While giving input it's completely ok but when I tried to access the fee data, it's showing nothing in fee's column .
在输入时完全可以,但是当我尝试访问费用数据时,费用列中什么都没有显示。 How do I solve it?
我该如何解决?
Course Model: 课程模式:
<?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');
}
}
Fee Model: 收费模式:
<?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');
}
}
Controller: 控制器:
public function listofCourse(){
$course=\App\Course::all();
return view('listofCourse',compact('course'));
}
View Page: 查看页面:
<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>
It seems that you have written the relationship wrongly... just do this. 看来您写错了这种关系……只要这样做。
Keep in Mind, Course Has The Fee
means Course
is must, so relation should start from Course
side towards Fee
. 切记,
Course Has The Fee
意味着Course
是必须的,因此关系应该从Course
方开始向Fee
。
Your Course Model 您的课程模型
class Course extends Model
{
protected $table='courses';
protected $fillable = ['name'];
public function fee(){
return $this->hasOne('App\Fee','course_id', 'id');
}
}
Your Fee Model 您的费用模型
class Fee extends Model
{
protected $table='fees';
protected $fillable = ['fee','course_id'];
public function course()
{
return $this->belongsTO('App\Course', 'course_id', 'id');
}
}
Now you can get the relationship by doing this. 现在,您可以通过执行此操作来建立关系。
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'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.