0

How would I refactor the code below so that there is only one reject function not two and have only one call to the db instead of three. I am also trying to not have any duplicates.

$latestListings = $repo->whereExclusive(['property_status' => 'Active'],['created_at' => 'desc'],[],0, 4);

    $latestListingsIds = $latestListings->map(function (Listing $listing) {
        return $listing->id;
    })->toArray();

    $highCflListings = $repo->whereExclusive(['property_status' => 'Active'],['cfl' => 'desc'],[],0, 4);

    $highCflListingIds = $highCflListings->map(function (Listing $listing) {
        return $listing->id;
    })->toArray();


    $highCflListingsOccupied = $repo->whereExclusive(
        ['property_status' => 'Active', 'occupied_percentage' => 100],
        ['cfl' => 'desc'],
        [],
        0,
        12
    )->reject(function (Listing $listing) use ($latestListingsIds) {
        return in_array($listing->id, $latestListingsIds);
    })->reject(function (Listing $listing) use ($highCflListingIds) {
        return in_array($listing->id, $highCflListingIds);
    })->take(4);
Crystal
  • 1,425
  • 1
  • 22
  • 34

1 Answers1

1

I don’t know how you’re setting $latestListingsIds and $highCflListingIds but if these are just arrays of IDs, combine them and reject on those:

$exclude = $latestListingsIds + $highCflListingIds;

$highCflListingsOccupied = $repo->whereExclusive(['property_status' => 'Active', 'occupied_percentage' => 100], ['cfl' => 'desc'], [], 0, 12)
    ->reject(function (Listing $listing) use ($exclude) {
        return in_array($listing->id, $exclude);
    })
    ->take(4);
Martin Bean
  • 38,379
  • 25
  • 128
  • 201
  • Thank you for your answer, however this seems to allow duplicates. What I'm trying to do is not have any duplicates. – Crystal Dec 07 '16 at 18:27
  • Duplicates of what? It rejects any records with a primary key value that occurs in `$exclude`. – Martin Bean Dec 07 '16 at 19:55