如何在laravel中从3个条件中获取所有数据?

时间:2019-01-14 07:45:13

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

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

1 个答案:

答案 0 :(得分:0)

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