【问题标题】:How would I combine two reject functions with PHP/ Laravel?我如何将两个拒绝函数与 PHP/Laravel 结合起来?
【发布时间】:2016-12-07 18:00:02
【问题描述】:

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

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

【问题讨论】:

    标签: laravel pdp


    【解决方案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);
    

    【讨论】:

    • 感谢您的回答,但这似乎允许重复。我想要做的是没有任何重复。
    • 复制什么?它拒绝主键值出现在$exclude 中的任何记录。
    猜你喜欢
    • 2011-08-02
    • 2020-06-13
    • 2012-09-16
    • 2021-09-28
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多