0

我将如何重构下面的代码,以便只有一个拒绝函数而不是两个,并且只有一个对数据库的调用而不是三个。我也试图没有任何重复。

$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);
4

1 回答 1

1

我不知道您是如何设置的$latestListingsIds$highCflListingIds但是如果这些只是 ID 数组,请将它们组合起来并拒绝:

$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);
于 2016-12-07T18:05:42.123 回答