如何在 laravel Eloquent ORM 中为具有不同条件的多个模型创建连接查询
How to create join query for multiple models with separate conditions in laravel Eloquent ORM
我想为具有单独(模型)条件的多个模型创建连接查询。
我创建了以下查询:
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'
studentinformation 模型名称的 Table 是“StudentAdmissionModel”。
studentattandence 模型名称的 Table 是“StudentAttandenceModel”。
我该怎么做 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;
}
我想为具有单独(模型)条件的多个模型创建连接查询。
我创建了以下查询:
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'
studentinformation 模型名称的 Table 是“StudentAdmissionModel”。
studentattandence 模型名称的Table 是“StudentAttandenceModel”。
我该怎么做 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;
}