Join Query in magento 2
-
30-12-2020 - |
質問
The below code entry is already in DB, Now I need to add one field to customer id and want to rerun this code via programmatically.
$this->getSelect()->join(
['detail' => $this->getReviewDetailTable()], 'main_table.review_id = detail.review_id', ['detail_id', 'title', 'detail', 'nickname', 'customer_id']
);
I have created a custom module from for Product Review. In above I have overrides the Magento review collection class, while overriding this part shows error as
You cannot define a correlation name 'detail' more than once
So Now In my override class I have added the one more field, But DB has the entry already. I also need to handle this while updating or overriding in my class so pls provide me a solution
解決
Check below query
$this->getSelect()->join(
['details' => $this->getReviewDetailTable()], 'main_table.review_id = details.review_id', ['detail_id', 'title', 'detail', 'nickname', 'customer_id']
);
他のヒント
I know this question has an accepted answer but in this case the line parent::_iniselect() is doing reference to
\Magento\Review\Model\ResourceModel\Review\Collection
(the new parent) which extends from:
\Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
(the original parent) so you should change it for
\Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::_initSelect();
as shown below:
protected function _initSelect()
{
//parent::_initSelect();
\Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::_initSelect();
$this->getSelect()->join(
['detail' => $this->getReviewDetailTable()],
'main_table.review_id = detail.review_id',
['detail_id', 'title', 'detail', 'nickname', 'customer_id']
);
}
What is happening is that your join is already set. What you could is to check whether the join was already set or not.
Something like this:
try {
$this->getSelect()->join(
['details' => $this->getReviewDetailTable()], 'main_table.review_id = details.review_id',
['detail_id', 'title', 'detail', 'nickname', 'customer_id']
);
} catch (\Exception $e) {
...
}
I would change the alias details
to something more unique.