# hasMany association but using limit(1) ('hasOne')

**URL:** <https://discourse.cakephp.org/t/hasmany-association-but-using-limit-1-hasone/9769>\
**Category:** Need Help\
**Tags:** help\
**Created:** [October 4, 2021, 10:48am UTC](https://discourse.cakephp.org/t/hasmany-association-but-using-limit-1-hasone/9769 "2021-10-04T10:48:41Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![maurobr1](https://avatars.discourse-cdn.com/v4/letter/m/d2c977/32.png) [@maurobr1](https://discourse.cakephp.org/u/maurobr1)\
**Post date:** [October 4, 2021, 10:48am UTC](https://discourse.cakephp.org/t/hasmany-association-but-using-limit-1-hasone/9769/1 "2021-10-04T10:48:41Z")

</div>

I have the following structure:  
Animals[id, weight]  
Records[date, animal\_id, weight]  
An animal has a lot of records on different dates and the hasMany association is working fine.  
But in some cases, I just want to show the last record (according to date) for each animal. I’ve tried creating a hasOne record association with no success.  
When Im using “$this-\>Animals-\>get($id, [‘contain’=\> [‘Record’]]);” the animal-\>record its not the latest one but the first one.  
When Im using “$this-\>Animals-\>find()-\>contain([‘Record’])-\>all();” all the animals-\>record are null except for the first animal.

```
class AnimalsTable extends Table {

    $this->hasMany('Records', [
        'bindingKey' => 'id',
        'foreignKey' => 'animal_id',
    ]);

    $this->hasOne('Record', [
        'className' => 'Records',
        'foreignKey' => 'animal_id',
        'strategy' => 'select',
        'sort' => ['Records.date' => 'DESC'],
        'conditions' => function ($e, $query) {
            $query->limit(1);
            return [];
        }
    ]);
}

```

PD: There’s a very good explanation from mdn in [cakephp - How to limit contained associations per record/group? - Stack Overflow](https://stackoverflow.com/questions/30241975/how-to-limit-contained-associations-per-record-group) but it is from 6 years ago.

---

<div class="post-metadata">

**Author:** ![ndm](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/ndm/32/2234_2.png) [@ndm](https://discourse.cakephp.org/u/ndm)\
**Post date:** [October 4, 2021, 4:05pm UTC](https://discourse.cakephp.org/t/hasmany-association-but-using-limit-1-hasone/9769/2 "2021-10-04T16:05:07Z")

</div>

> [@maurobr1](#):
>
> PD: There’s a very good explanation from mdn in [cakephp - How to limit contained associations per record/group? - Stack Overflow](https://stackoverflow.com/questions/30241975/how-to-limit-contained-associations-per-record-group) but it is from 6 years ago.

But I’ve updated it relatively recently with a new plugin solution, and the rest is still the status quo I’m afraid 😉

---

<div class="post-metadata">

**Author:** ![yousuo](https://avatars.discourse-cdn.com/v4/letter/y/898d66/32.png) [@yousuo](https://discourse.cakephp.org/u/yousuo)\
**Post date:** [October 5, 2021, 1:41pm UTC](https://discourse.cakephp.org/t/hasmany-association-but-using-limit-1-hasone/9769/3 "2021-10-05T13:41:57Z")

</div>

> [@maurobr1](#):
>
> ```auto
> $this->hasOne('Record', [
> 'className' => 'Records',
> 'foreignKey' => 'animal_id',
> 'strategy' => 'select',
> 'sort' => ['Records.date' => 'DESC'],
> 'conditions' => function ($e, $query) {
> $query->limit(1);
> return [];
> }
> ]);
> 
> ```

Try using a finder instead ([hasOne association](https://book.cakephp.org/4/en/orm/associations.html#hasone-associations))

```auto
$this->hasOne('Record', [
        'className' => 'Records',
        'foreignKey' => 'animal_id',
        'strategy' => 'select',        
    ])->setFinder('latestDateRecord');

// Add this custom finder in Model/Table/RecordsTable.php
public function findLatestDateRecord(Query $query, array $options)
{
	$query->where(['add in your own conditions here'])
	->order(['Records.date' => 'DESC'])
	->limit(1);
	// debug your query here for more info
	debug( $query->sql() );
	return $query;
}

```

---

<div class="post-metadata">

**Author:** ![ndm](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/ndm/32/2234_2.png) [@ndm](https://discourse.cakephp.org/u/ndm)\
**Post date:** [October 5, 2021, 2:57pm UTC](https://discourse.cakephp.org/t/hasmany-association-but-using-limit-1-hasone/9769/4 "2021-10-05T14:57:28Z")

</div>

@yousuo That won’t work, a custom finder doesn’t change how the records are looked up, the `select` strategy will still use a single query to retrieve all associated records (like `SELECT ... FROM records WHERE parent_id IN (1,2,3,4, ....)`, and that’s where the limit will be applied, thus it will still result in only 1 overall associated record to be retrieved, _not_ 1 associated record per parent.
