gpt4 book ai didi

php - 如何在 laravel Eloquent ORM 中为具有不同条件的多个模型创建连接查询

转载 作者:太空宇宙 更新时间:2023-11-03 12:02:42 25 4
gpt4 key购买 nike

我想为具有单独(模型)条件的多个模型创建连接查询。

我创建了以下查询:

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 模型名称表为“StudentAdmissionModel”。

studentattandence 模型名称表是“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;
}

关于php - 如何在 laravel Eloquent ORM 中为具有不同条件的多个模型创建连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28380615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com