如何将两个拒绝函数与PHP / Laravel结合使用?

时间:2016-12-07 18:00:02

标签: laravel pdp

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

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

1 个答案:

答案 0 :(得分:1)

我不知道您是如何设置$latestListingsIds$highCflListingIds的,但如果这些只是ID数组,请将它们合并并拒绝这些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);