2

I'm trying to load all of the associated entries to another table that has a foreign key

protected function _getLoadSelect($field, $value, $object)
{
    $field = $this->getConnection()->quoteIdentifier(sprintf('%s.%s', $this->getMainTable(), $field));

    $select = $this->getConnection()->select()->from($this->getMainTable())->where($field . '=?', $value)
    ->join(
        ['second_table_alias' => 'second_table'],
        'first_table.entity_id = second_table_alias.entity_id'
    )
    ->group('second_table_alias.entity_id');

    return $select;
}

There are multiple rows that share that entity_id and if I switch between left join and join (inner join) it returns different results.

Is it possible to get an array of all rows with that entity_id from the secondary table? What am I doing wrong?

2 Answers 2

1

The returned result needs to be fetched in order to retrieve the results:

$select = $entity->_getLoadSelect();
$data = $this->getConnection()->fetchAll($select);
2
  • 1
    _getLoadSelect is used by other methods (like load for example) and it should return an instance of a select, not the actual results.
    – Marius
    Oct 31, 2016 at 16:48
  • @Marius true that I'm gonna edit my answer Oct 31, 2016 at 16:52
1

There only reason (I see) to load all the associated entities when the load select is executed is to be able to apply a filter on those loaded entities.
If you apply a filter inside the load select that should get only one record (or none) it should be OK.
So you can apply your filter directly in this method.
Take a look at the method from the CMS module
If you just need the associated entities, I recommend you a separate method afterLoad for example, that will just query your secondary table and give you what you need.
Or better yet, have a method that retrieves the results when needed the first time, then stores them in a member variable.
This way you get lazy loading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.