【问题标题】:How to fetch all data from 3 tables with condition in laravel?如何从laravel中的3个有条件的表中获取所有数据?
【发布时间】:2019-01-14 17:57:42
【问题描述】:

我有 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

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-5.2 laravel-5.1


    【解决方案1】:

    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');     
    }
    

    SchoolDetails 模型

    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
    

    【讨论】:

    • 照你说的做,但我想说我有一所学校有一个学校的详细信息,但是学校可以有多个录取请检查,有一些错误
    • 已编辑。因此,在一对多关系的情况下,学校模型将具有 hasMany 入学关系,而 Inverse 将是 belongsTo
    • 照你说的做了,我得到了这两个 {{ $school->School->name}} {{ $school->start_date }} 的结果,但试图获得非对象的属性{{ $school->School->SchoolDetails->contact_phone}}
    • 你能帮帮我吗
    • 再次编辑对此感到抱歉。这次我创建了一个新项目,然后自己检查了它。 SchoolDetails 关系存在问题。请查看更改
    猜你喜欢
    • 2019-04-18
    • 2020-01-06
    • 2023-03-23
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多