我正在尝试在付款页面上显示付款表信息。
payments{student_id, course_id, payment_type_id}
students{id, name}
courses{id, name}
payment_types{id,name}
对于列> course_id(在付款表中)它显示了付款页面中的课程名称。但是对于其他两列,它没有发布。我的错误是什么。谢谢你提前!
这是我的 Payment.php 模型
protected $fillable = [
'student_id',
'course_id',
'payment_types_list_id',
];
protected $filter = [
'page' => false,
'_token' => false,
'student_id' => '=',
'course_id' => '=',
'payment_types_list_id' => '=',
];
public function Payment() {
return $this->hasOne('App\Payment');
}
public function course() {
return $this->belongsTo('App\Course');
}
public function students() {
return $this->belongsToMany('App\Student');
}
public function PaymentType() {
return $this->belongsTo('App\PaymentType');
}
这里 payments_table
public function up() {
Schema::create('payments', function(Blueprint $table)
{
$table->increments('id');
$table->integer('student_id')->unsigned()->index();
$table->foreign('student_id')->references('id')->on('students');
$table->integer('course_id')->unsigned()->index();
$table->foreign('course_id')->references('id')->on('courses');
$table->integer('payment_types_list_id');
$table->foreign('payment_types_list_id')
->references('id')->on('payment_types_list');
$table->timestamps();
});
}
这是 PaymentController.php
public function index(Request $request) {
$filter = $request->input();
$sort = $request->query();
$payments = Payment::filter($filter)->sort($sort)->paginate(10);
foreach(PaymentType::all() as $payment_type) {
$payment_types[$payment_type->id] = $payment_type->name;
}
foreach(Course::all() as $course) {
$courses[$course->id] = $course->name;
}
foreach(Student::all() as $student) {
$students[$student->id] = $student->name;
}
return view('payments.index', compact('payments', 'filter','courses','students', 'payment_types'));
}
这是 Payment / index.php
@forelse ($payments as $key => $payment)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $payment->student['name'] }}</td>
<td>{{ $payment->course['name']}}</td>
<td>{{$payment->payment_types_list['name']}}</td>
</tr>
@endforelse
答案 0 :(得分:1)
所以问题在于关系的名称。定义关系时,应使用相同的定义名称访问它。
例如 -
如果您的关系名称为PaymentType
,那么您应该访问以下关系:
{{ $payment->PaymentType->name }}
OR
{{ $payment->PaymentType['name'] }}
对于学生关系,它应该是belongsTo
而不是belongsToMany
所以 -
public function student()
{
return $this->belongsTo('App\Student');
}
然后您可以按以下方式访问它:
{{ $payment->student->name }}