From af7fae25d9dfc1fa4dfdb5939febbbd7544d34e8 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 2 Jan 2024 16:39:36 +0300 Subject: [PATCH] Unique models (#207) Co-authored-by: Victor Isadov --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 2da962f..61e962b 100644 --- a/README.md +++ b/README.md @@ -400,6 +400,27 @@ class Country extends Model } ``` +#### Getting Unique Models +Sometimes you have relationship which has duplicate models in the result. In simple case you call `unique` on final Collection and that's all. + +But if you need unique records on DB level (for example for pagination) you can use this approach: + +```php +// HasManyDeep relation Warehouse -> WarehousePosition -> Product +$warehouse->products() + // GROUP BY target table primary key + ->groupBy("products.id") + + // get underlying Builder without laravel_through_key in SELECT + ->getQuery() + + // SELECT columns only from target table + ->select('products.*') + ->get(); +``` + +Instead of `groupBy` you can call `distinct`. That should works too. + #### Composite Keys If multiple columns need to match between two tables, you can define a composite key with the `CompositeKey` class.