我无法从数据透视表中的额外列访问数据。
我有两个模型(Grado和Subject)(这是一个用于管理k-12学校成绩的较大应用程序的一部分)。Grado是指年级,即一年级,二年级等。我希望管理员能够将给定年份中的科目与年级相关联。
mysql枢纽分析表grado_subject包含:
id_grado_subject
year_grado_subject //年份-我要访问的列
degree_id_degrees //度的外键ID
subject_id_subjects //主题的外键ID
created_at
Updated_at
Grado模型:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Grado extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'grados';
protected $primaryKey = "id_grados";
protected $fillable = array('name_grados');
public static $rules = array(
);
public function subject()
{
return $this->belongsToMany('Subject','grado_subject','grados_id_grados','subjects_id_subjects')
->withPivot('year_grado_subject')
->withTimestamps();
}
public function groups()
{
return $this->hasMany('Group','id_grados','grados_id_grados');
}
}
主题模型:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Subject extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'subjects';
protected $primaryKey = "id_subjects";
protected $fillable = array('engSpanExtra_subjects', 'name_subjects','IntGrade_subjects');
public static $rules = array(
'name_subjects' => 'required',
'engSpanExtra_subjects' => 'required',
'IntGrade_subjects'=> 'required'
);
public function grado()
{
return $this->belongsToMany('Grado','grado_subject','subjects_id_subjects','grados_id_grados')
->withPivot('year_grado_subject')
->withTimestamps();
}
public function teacher()
{
return $this->belongsToMany('Teacher','subject_teacher','subjects_id_subjects','teachers_id_teachers');
}
}
在GradoController中:
class GradoController extends \BaseController {
public function index()
{
$grados = Grado::find(1);
$years = $grados->pivot->year_grado_subject;// line I get error on
return $years;
$grados->toarray();
return View::make('grados.index',compact('grados', 'years'));
}
当我尝试检索与grade_subject相关的所有年份时,出现错误:尝试获取非对象的属性。
任何帮助将不胜感激!
该pivot
属性是由belongsToMany
关系生成的,因此它存在于由该关系加载的对象(对象)上,而不是主要对象(grado)上。
例如:
// primary object is grado
$grado = Grado::find(1);
// loop through related subjects
foreach($grado->subject as $subject) {
// pivot attribute exists on related subject
echo $subject->pivot->year_grado_subject;
}
或者,如果您采用相反的方式:
// primary object is subject
$subject = Subject::find(1);
// loop through related grados
foreach($subject->grado as $grado) {
// pivot attribute exists on related grado
echo $grado->pivot->year_grado_subject;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句