【问题标题】:How to create join query for multiple models with separate conditions in laravel Eloquent ORM如何在 laravel Eloquent ORM 中为具有不同条件的多个模型创建连接查询
【发布时间】:2015-04-07 11:19:04
【问题描述】:

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

我创建了以下查询:

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。

【问题讨论】:

    标签: php mysql laravel laravel-4 eloquent


    【解决方案1】:

    您需要在 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;
    }
    

    【讨论】:

    • 仅供参考,您可以使用->where('Age', '2') 而不是->where('Age','=','2')
    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 2015-03-04
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多