Laravel 5.2在从数据库获取数据时尝试获取非对象的属性
我在使用laravel 5.2我有两个模型 教授:Laravel 5.2在从数据库获取数据时尝试获取非对象的属性,laravel,orm,laravel-5.2,blade,Laravel,Orm,Laravel 5.2,Blade,我在使用laravel 5.2我有两个模型 教授: class Prof extends Model { protected $fillable=array('nom','prenom','age','mail'); public function matieres(){ return $this->hasMany(Matiere::class,'id_prof'); } } 马蒂埃: class Matiere extends Model { protec
class Prof extends Model
{
protected $fillable=array('nom','prenom','age','mail');
public function matieres(){
return $this->hasMany(Matiere::class,'id_prof');
}
}
马蒂埃:
class Matiere extends Model
{
protected $fillable=array('Nom');
public function profs(){
return $this->BelongsTo(Prof::class,'id_prof');
}
}
在MatierController中,我有一种方法可以提供所有Matiere:
public function index()
{
$matiere = Matiere::all();
return view('Matiere.index',compact('matiere'));
}
在我看来,我显示了我的Matiere列表以及教授这门学科的教授的姓名(Matiere)
但是我得到了这个错误
尝试获取非对象的属性
我怎样才能解决这个问题?thnks首先,您不需要在hasMany和BelongsTo中指定外键,这有点神奇,但通常雄辩的是,您能够理解并从外键中搜索正确的id(如果您在迁移文件中创建了外键关系) 其次,当您在blade代码中执行foreach时,调用
$mat->profs
,如果我没有弄错,它将返回一个集合或数组,而不是返回一个对象数组。这就是为什么在尝试获取非对象的属性时会出现错误
因此,要解决这个问题,您需要执行以下操作
@foreach ($matiere as $mat)
@foreach ($mat->profs() as $pr)
{{$pr->prenom}}
@endforeach
@endforeach
如果在$mat
对象上调用方法profs()
,则它将返回一个对象数组
Bonne chance pour la suite;) 我只使用一个foreach来修复它
@foreach ($matiere as $mat)
{{ $mat->profs->prenom}}
@endforeach
太感谢你了:)
@foreach ($matiere as $mat)
{{ $mat->profs->prenom}}
@endforeach