簡體   English   中英

如何在 PHP Laravel 中循環 Eloquent Collection?

[英]How can I loop a Eloquent Collection in PHP Laravel?

我正在嘗試使用 Laravel Jetstream Teams 進行自動注冊。 由於 Jetstreams 需要一個“個人團隊”,而我的應用程序要求用戶與特定團隊分開,我找到了一種方法來attach用戶attach到團隊,然后switchTeam團隊,以便他們當前的團隊像他們的個人團隊一樣加載。

為此,我禁用了手動注冊,禁用了創建新團隊的功能並禁用了人們離開團隊的功能。 這節省了從 Jetsteam 中刪除個人團隊的時間。

這樣做時,由於應用程序自動創建用戶(從電子表格),我還需要將團隊分配給該用戶。 我試圖遍歷每個Team::all但響應是一個數組,因此我的array_filter由於對象被作為參數給出而返回錯誤。

protected function assignTeam(User $user)
{
    $team = array_filter(Team::all(), function(Team $team) {
        // teamToAssign dervies from Spreadsheet data
        return strtoupper($team->name) === strtoupper($this->teamToAssign);
    });
    
    if(!empty($team)) // User error can exist in data
    {
        Team::find($team->id)->users()->attach($user, ['role' => 'participant']);
        User::find($user->id)->switchTeam(Team::find($team->id));
        return;
    }

    // TODO: Deal with user error
}

任何人都可以闡明我如何解決這個問題嗎? 我是 Laravel 的新手,不確定是否有更好的方法來循環遍歷Eloquent Collections 提前謝謝了。

你可以做

$teams = Team::all()->toArray(); // this will convert collection to array 

// or

Team::all()->each(function (Team $team) { // this will allow you to loop through the collection 

   // TODO ...

});

Team::all()->filter(function (Team $team) { // this will allow you to filter unwanted instances

   // TODO ...

});

有關 Laravel Collection Helper 方法的更多信息,請點擊此處

您可以使用方法過濾器來過濾您的集合,如以下鏈接所示:

https://laravel.com/docs/8.x/collections#method-filter

在處理集合時,您還可以在這里找到很多方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM