我想为具有单独(模型)条件的多个模型创建联接查询。
我创建了以下查询:
select * from studentinformation as s left join studentattandence a on s.id =
a.studentid where s.PersonalFirstName='Kathi' and s.PersonalLastName='irfan'
and s.Age='2' and s.gender ='Male' and s.StudentCourse='1' and
s.GuardianFirstName='test' and s.GuardianLastName = 'test' and a.date
BETWEEN '2015-02-01' AND '2015-02-07'
学生信息模型名称表为"StudentAdmissionModel"。
学生成就模型名称表为"学习成就模型"。
我怎么能做这个laravel Eloquent ORM。
您需要在StudentAdmissionModel中声明两者之间的关系,它看起来像这样:
class StudentAdmissionModel extends Eloquent {
public function attendance()
{
// Assuming a one-to-one relationship
return $this->hasOne('StudentAttandenceModel','studentid');
}
}
然后您就可以使用whereHas()函数来查询关系:
$admissions = StudentAdmissionModel::where('PersonalFirstName','=','Kathi')
->where('PersonalLastName','=','irfan')
->where('Age','=','2')
->where('gender','=','Male')
->where('StudentCourse','=','1')
->where('GuardianFirstName','=','test')
->where('GuardianLastName ','=','test')
->whereHas('attendance',function($q)
{
$q->whereBetween('date', array('2015-02-01','2015-02-07'));
})
->with('attendance') // Optional eager loading, but recommended
->get();
您可以访问以下字段:
foreach( $admissions as $admission){
echo $admission->gender;
// or
echo $admission->attendance->date;
}