laravel - 如何从laravel中的3个有条件的表中获取所有数据?
问题描述
我有 3 个表学校,学校详细信息和录取,我想在索引页面中获取所有数据我该怎么做,由于关系,我正在获取学校和录取表的数据,但不是学校详细信息,请检查并帮助
school
id
name
name
mobile
city
schooldetails
id
school_id(foreign key of school id)
contact_person
admission
id
school_id(foreign key of school_deatils id)
admission_classes
start_date
end_date
My function
public function schoolslist($class='', $city='')
{
$schools = Admission::where('admission_classes', 'like', "%{$class}%")->where('status', '1')->orderBy('id','desc')->whereHas('school', function($query) use($city) {
$query->where('city', 'like', $city);
})->paginate(10);
return view('frontend.index',compact('schools'));
}
my Admission model
public function School()
{
return $this->belongsTo('App\School');
}
public function SchoolDetails()
{
return $this->belongsTo('App\SchoolDetails');
}
My view
@foreach($schools as $i => $school)
{{ $school->School->name}} from user table Ravi
{{ $school->SchoolDetails->contact_person}} //from school_Details table No result
{{ $school->start_date }} //from admission table date 11/22/2018
@enforeach
解决方案
SchoolDetails 关系应该与学校而不是加入,因此从入学模型中删除 SchoolDetails() 并将其添加到学校模型
学校模式:
public function Admission()
{
return $this->hasMany('App\Admission');
}
public function SchoolDetails()
{
return $this->hasOne('App\SchoolDetails'); \\Edited
}
录取模式:
public function School()
{
return $this->belongsTo('App\School');
}
学校详细型号:
public function School()
{
return $this->belongsTo('App\School'); \\Edited
}
然后您可以相应地更改您的视图:
@foreach($schools as $i => $school)
{{ $school->School->name}} from user table Ravi
{{ $school->School->SchoolDetails->contact_person}} // This Line is changed
{{ $school->start_date }}
@enforeach
推荐阅读
- linux - 如何在linux中配置连接到usb的调制解调器?
- ios - macbook m1中没有发生这样的模块'firebase'错误
- vba - 打印为 PDF 时从 Excel 工作表重命名 Word 宏
- javascript - Dash React 下拉组件:无法从浏览器控制台打开
- c# - json .net 5 blazor中的日期时间空序列化如何
- reactjs - 如何在 React 的 React.createElement() 中定义 img 标签?
- python - 为什么我会收到此“'builtin_function_or_method' 对象没有属性 'choice'”错误?
- vuejs3 - 在Vuejs3中如何在CoreUI中单击关闭图标时禁用或关闭模式
- apache-kafka - 卡夫卡经纪人倒闭
- reactjs - 如何在玩笑测试中找到 svg?