我试图在模板中显示两个表的列,但没有成功
模板:
@foreach ($LatestSeeker_list_adv as $ads)
<span>ads id</span><span>{{ $ads->advertise->id }}</span>
<span>inf id</span><span>{{ $ads->information->id }}</span>
@endforeach
控制器:
public function SeekerLatest()
{
$LatestSeeker_list_adv = Advertise_Model::all();
return view('Users.Seeker.LatestAds.index',compact('LatestSeeker_list_adv','LatestSeeker_list_inf'));
}
广告模式:
public function Information()
{
return $this->hasOne('App'Information_Model');
}
信息模型:
public function Advertise()
{
return $this->belongsTo('App'Advertise_Model');
}
广告迁移:
Schema::table('advertise', function($table) {
$table->foreign('information_id')->references('id')->on('information');
});
编辑:
错误:
正在尝试获取非对象的属性(视图:C: ''Users''Aghapesae''Desktop''baroot''resources''views''Users''Seeker''LatestAds''Index.blade.php)
使用with
public function SeekerLatest()
{
$LatestSeeker_list_adv = Advertise_Model::with('Information')->get();
return view('Users.Seeker.LatestAds.index',compact('LatestSeeker_list_adv','LatestSeeker_list_inf'));
}
在视图中,你可以这样做:
@foreach ($LatestSeeker_list_adv as $ads)
<span>ads id</span><span>{{ $ads->id }}</span>
<span>inf id</span><span>{{ $ads->Information->id }}</span>
@endforeach