Skip to content

Commit

Permalink
Unique models (#207)
Browse files Browse the repository at this point in the history
Co-authored-by: Victor Isadov <[email protected]>
  • Loading branch information
decadence and Victor Isadov authored Jan 2, 2024
1 parent ad04a75 commit af7fae2
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit af7fae2

Please sign in to comment.