我使用的是laravel 5.7,这种关系是每个学生都属于一个程序,而我正在尝试使用{{ $student->programs->title }}
但是有错误
ErrorException(E_ERROR) 尝试获取非对象的属性“标题”(视图:D:\ Work \ UnitOne \ BackEnd \ UniLara \ resources \ views \ admin \ students \ index.blade.php)
这是我的学生模式 l
<?php
class Student extends Model {
protected $fillable = [
'name', 'country', 'program_id', 'image'
];
public function programs() {
return $this->belongsTo(Program::class);
}
}
这是我的程序模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Program extends Model {
protected $fillable = [
'title', 'description', 'image'
];
public function students() {
return $this->hasMany(Student::class);
}
}
这是我的 StudentsController
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Students\CreateStudentsRequest;
use App\Http\Requests\Students\UpdateStudentsRequest;
use App\Program;
use App\Student;
use Illuminate\Http\Request;
class StudentsController extends Controller {
public function index() {
return view('admin.students.index')->with('students', Student::paginate(5));
}
}
这是刀片的最后一件事,这是我打电话给{{ $student->programs->title }}
@foreach($students as $student)
<tr>
<td><img src="{{ asset($student->image) }}" alt="{{ $student->image }}"></td>
<td>{{ $student->name }}</td>
<td>{{ $student->country }}</td>
<td>{{ student->programs->title }}</td>
</tr>
@endforeach
答案 0 :(得分:0)
更改您的关系名称。如果您未在关系定义中指定外键,Laravel会在数据库中查找relation_primarykey
之类的列。在您的情况下,您的关系为programs
,但您的数据库列为program_id
。额外的s
引起了问题。因此,请使用以下任一选项。
public function program()
{
return $this->belongsTo(Program::class);
}
或
public function programs()
{
return $this->belongsTo(Program::class, 'program_id');
}