# QueryBuilder - two models and a subquery

**URL:** <https://discourse.cakephp.org/t/querybuilder-two-models-and-a-subquery/9484>\
**Category:** Need Help\
**Created:** [July 3, 2021, 4:21pm UTC](https://discourse.cakephp.org/t/querybuilder-two-models-and-a-subquery/9484 "2021-07-03T16:21:26Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![frfr31](https://avatars.discourse-cdn.com/v4/letter/f/9d8465/32.png) [@frfr31](https://discourse.cakephp.org/u/frfr31)\
**Post date:** [July 3, 2021, 4:21pm UTC](https://discourse.cakephp.org/t/querybuilder-two-models-and-a-subquery/9484/1 "2021-07-03T16:21:27Z")

</div>

Good evening,

I’m using cakePhp 4 and I get stuck with a query. I have a Students and a Studentmarks table. I’d like to retrieve students with their last mark, including students who may have not marks yet. My SQL works just fine in phpmyadmin but I can’t push it to cakePhp.  
Here is the SQL:

```auto
SELECT * FROM students AS s LEFT JOIN studentmarks AS m ON s.id = m.student_id
WHERE m.markdate = (SELECT MAX(markdate) FROM studentmarks WHERE studentmarks.student_id = students.id)
OR m.markdate IS NULL

```

Here is my closest (but still far) try to get something working but there is obviously something I understand wrongly so any help is the most welcome:

```auto
$subquery = "(SELECT MAX(markdate) FROM studentmarks WHERE studentmarks.student_id = students.id);
$this->paginate = [
    'contain' => ['Studentmarks'],
    'conditions' => $subquery,
];
$students = $this->paginate($this->Students);

```

Thanks in advance for any tips!
