【发布时间】:2018-12-08 21:03:08
【问题描述】:
我有 2 张桌子 attendance 和 student。我正在尝试使用attendance 表中的student 外键从student 表中检索我的stud_name。我有一个控制器,它返回来自attendance 模型的所有结果的视图。我还在student 和attendance 模型中添加了关系,但是每当我尝试访问视图时,我都会遇到错误异常尝试获取非对象的属性'stud_name'。谁能帮帮我?
考勤控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Attendance;
class GenerateReportController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$attendance = Attendance::with('student')->get();
return view('generate')->with('attendance',$attendance);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Student.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
//Table
protected $table = 'students';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamp = true;
public function programme(){
return $this->belongsTo('App\Programme');
}
public function attendance(){
return $this->hasMany('App\Attendance');
}
}
Attendance.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Attendance extends Model
{
//Table
protected $table = 'attendance';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamp = true;
protected $fillable = [
'att_status','date','time',
];
public function student()
{
return $this->belongsTo('App\Student','s_id');
}
刀片文件
@foreach($attendance as $att)
<tr>
<td>{{$att->stud_Id->stud_name}}</td>
//Other Data
</tr>
@endforeach
附加信息
所有主键都命名为“id”的原因是因为我使用的是 voyager,它不允许覆盖主键名称。
dd($attendance)
【问题讨论】: