2014-09-24 223 views
11

這是一個過於簡化的例子,不適合我。如何(使用這種方法,我知道有更好的方法,如果我真的想要這個特定的結果),我可以得到總用戶數?如何獲得Laravel塊的返回值?

User::chunk(200, function($users) 
{ 
    return count($users); 
}); 

這將返回NULL。任何想法如何從塊函數獲得返回值?

編輯:

這裏可能是一個更好的例子:

$processed_users = DB::table('users')->chunk(200, function($users) 
{ 
    // Do something with this batch of users. Now I'd like to keep track of how many I processed. Perhaps this is a background command that runs on a scheduled task. 
    $processed_users = count($users); 
    return $processed_users; 
}); 
echo $processed_users; // returns null 
+0

等等,你想得到的總用戶數,你不需要任何數據呢?似乎並不像塊是最有效的方法 – Ohgodwhy 2014-09-24 21:29:10

+0

@Ohgodwhy我試圖獲得塊函數的結果。請忽略示例的具體內容。 – Citizen 2014-09-24 21:30:13

+0

@Ohgodwhy我又增加了一個例子。 – Citizen 2014-09-24 21:34:47

回答

15

我不認爲你可以實現你這樣想的。匿名函數由chunk方法調用,因此您從閉包中返回的任何內容都被chunk所吞噬。由於chunk可能會將此匿名函數調用N次,因此它從它調用的閉包中返回任何內容是沒有意義的。

但是您可以向閉包提供對方法範圍變量的訪問,並允許閉包寫入該值,從而可以間接返回結果。您可以使用use關鍵字執行此操作,並確保通過引用傳遞中的方法範圍變量,這通過0​​修飾符實現。

這將工作,例如;

$count = 0; 
DB::table('users')->chunk(200, function($users) use (&$count) 
{ 
    Log::debug(count($users)); // will log the current iterations count 
    $count = $count + count($users); // will write the total count to our method var 
}); 
Log::debug($count); // will log the total count of records 
+0

它工作!謝謝! – Citizen 2014-09-24 22:01:20

+0

如果你需要更好的控制,你也可以使用你的類的屬性(在你的例子中,$ this-> count),並在塊的閉包中增加它。 – 2015-09-21 16:39:06

+1

對於那些覺得這不適合他們的人,對我來說,count會重置每個塊循環。我忘了將'&'參數添加到'use'語句中。如果你補充說它會正常工作。 – Maarten00 2017-07-12 11:35:39