0

I want to create join query for multiple models with separate (model) conditions.

I have create following query :

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'

Table of studentinformation model name is "StudentAdmissionModel".

Table of studentattandence model name is "StudentAttandenceModel".

How can i do this laravel Eloquent ORM.

1 Answer 1

3

You would need to declare a relationship between the two in the StudentAdmissionModel, which would look something like this:

class StudentAdmissionModel extends Eloquent {
    public function attendance()
    {
        // Assuming a one-to-one relationship
        return $this->hasOne('StudentAttandenceModel','studentid');
    }
}

Then you would be able to use the whereHas() function to query the relationship:

$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();

And you would be able to access the fields like this:

foreach( $admissions as $admission){
    echo $admission->gender;
    // or
    echo $admission->attendance->date;
}
Sign up to request clarification or add additional context in comments.

1 Comment

FYI, you can use ->where('Age', '2') rather than ->where('Age','=','2')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.