2016-12-07 32 views
0

我將如何重構下面的代碼,以便只有一個拒絕函數不是兩個,並且只有一個調用db而不是三個。我也試圖沒有任何重複。如何將兩個拒絕函數與PHP/Laravel結合使用?

$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

我不知道你是如何設置$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); 
+0

謝謝您的回答,然而這似乎允許重複。我想要做的是沒有任何重複。 – Crystal

+0

重複什麼?它拒絕任何具有'$ exclude'中出現的主鍵值的記錄。 –

相關問題