I have two content types lets say A and B. B has a entity reference field which references A. Now I can have multiple contents of type B that references the same content of type A. I have a views that lists fields of Content type A and I have used relationship to show some fields of B which references that particular row. But it shows duplicate entries which is obvious due to the left join. I was wondering is there any way in which I can only show rows of A's fields and B's field in which the B is the latest one. i.e. If there are two instances of B which references A then in the view only show rows in which the values of the one where B is the latest one.
If anyone has done this or has idea on how to do it, i would much appreciate it.
Thanks in advance.
Comments
Comment #1
SilviaT CreditAttribution: SilviaT commentedTrying to do the same here. Haven't found a solution yet.
Comment #2
nikita_tthttps://stackoverflow.com/a/2111420/8018195 This helped me with this issue.
Below is copy/paste of the stackoverflow answer (just in case):
This is an example of the greatest-n-per-group problem that has appeared regularly on StackOverflow.
Here's how I usually recommend solving it:
Explanation: given a row p1, there should be no row p2 with the same customer and a later date (or in the case of ties, a later id). When we find that to be true, then p1 is the most recent purchase for that customer.
Regarding indexes, I'd create a compound index in purchase over the columns (customer_id, date, id). That may allow the outer join to be done using a covering index. Be sure to test on your platform, because optimization is implementation-dependent. Use the features of your RDBMS to analyze the optimization plan. E.g. EXPLAIN on MySQL.
Useful comment:
If you want to include customers who never made a purchase, then change JOIN purchase p1 ON (c.id = p1.customer_id) to LEFT JOIN purchase p1 ON (c.id = p1.customer_id)
How this helped me (Drupal 8):
I created custom Relationship views plugin:
And created the Join view plugin (it is used in the custom Relationship plugin; see "order_based_entity_reverse_join").
This custom relationship plugin has to be added to the entity reference field (which references to A) in the entity type B.