0

I've got the following left join in my _prepareCollection(); method:

$collection->getSelect()->joinLeft(
        array('views_index' => "my_views_table"),
        'views_index.entity_id = main_table.entity_id',
        array('views'=>'count')
);

And then in my _prepareColumns() method I have:

$this->addColumn('views',
        array(
            'header'=> $this->__('Views'),
            'index' => 'views',
            'width' => '5%',
            'filter_index'  => 'views_index.count'
        )
);

When I load this page though, I get an error:

Item (Namespace_Module_Model_Mymodel) with the same id "{ID}" already exist

How is this conflict occurring?

Some background: Magento Custom Grid Redirect Error (On Join Attributes ONLY)

Would appreciate any help

Edit 1 The my_views_table consists of 3 columns, namely:

  1. id (primary key)
  2. entity_id
  3. count

1 Answer 1

1

You are joining one table to another with 1-N relationship.

It means for one row from the table A you get N rows from the table B

At the same time you fetch values to the magento collection, that use unique row ID and it throws the error.

Probably you need to group values, so if it is page views you can group by page_id and calculate count with aggregate function.

Note, that with the group by statement in the original SQL query you need custom approach for the pager as the default wont work. So sometimes it easier (but not faster or better) to use subqueries.

5
  • Thanks for the info. Why does this only happen when using my custom table? If I use the exact same join on an EAV table, there is no such problem.
    – Moose
    Commented Aug 29, 2014 at 11:01
  • It may depend on the number of records. If table B contains only 1 corresponding record for table A, you will see no error. But when you add the second record in the table B the result will contain 2 rows and you'll see the error.
    – Amasty
    Commented Aug 29, 2014 at 12:14
  • Please accept the answer or edit the question with the data samples so me or someone else can get better advice / exact code fix.
    – Amasty
    Commented Aug 29, 2014 at 12:16
  • I've updated my question.
    – Moose
    Commented Aug 29, 2014 at 12:59
  • So as you can see for one id (primary key) you have multiple entity_id. Add the groupby to the select object. $collection->getSelect()->group('id');
    – Amasty
    Commented Aug 29, 2014 at 14:40

Your Answer

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

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