ホームページ > バックエンド開発 > PHPチュートリアル > where instanceのタイプごとに収集オブジェクトをフィルタリングします

where instanceのタイプごとに収集オブジェクトをフィルタリングします

Karen Carpenter
リリース: 2025-03-06 02:02:08
オリジナル
314 人が閲覧しました

Filtering Collection Objects by Type with whereInstanceOf

LaravelのwhereInstanceOfメソッドは、オブジェクトタイプに基づいてセットをフィルタリングする簡潔な方法を提供します。これは、多型の関係または混合オブジェクトセットを扱うときに特に役立ちます。

以下は、whereInstanceOfUserPostを使用して

および
<?php
use App\Models\User;
use App\Models\Post;
use Illuminate\Support\Collection;

$collection = collect([
    new User(['name' => 'John']),
    new Post(['title' => 'Hello']),
    new User(['name' => 'Jane']),
]);

$users = $collection->whereInstanceOf(User::class);
ログイン後にコピー
オブジェクトのコレクションをフィルタリングする方法を示す簡単な例です。

より実用的な例を見てみましょう。さまざまな種類のアクティビティを含む通知フィードの処理。
<?php
namespace App\Services;

use App\Models\Comment;
use App\Models\Like;
use App\Models\Follow;
use Illuminate\Support\Collection;

class ActivityFeedService
{
    public function getUserFeed(User $user): array
    {
        // 获取所有活动
        $activities = collect([
            ...$user->comments()->latest()->limit(5)->get(),
            ...$user->likes()->latest()->limit(5)->get(),
            ...$user->follows()->latest()->limit(5)->get(),
        ]);
        // 按创建时间排序
        $activities = $activities->sortByDesc('created_at');

        return [
            'comments' => $activities->whereInstanceOf(Comment::class)
                ->map(fn (Comment $comment) => [
                    'type' => 'comment',
                    'text' => $comment->body,
                    'post_id' => $comment->post_id,
                    'created_at' => $comment->created_at
                ]),
            'likes' => $activities->whereInstanceOf(Like::class)
                ->map(fn (Like $like) => [
                    'type' => 'like',
                    'post_id' => $like->post_id,
                    'created_at' => $like->created_at
                ]),
            'follows' => $activities->whereInstanceOf(Follow::class)
                ->map(fn (Follow $follow) => [
                    'type' => 'follow',
                    'followed_user_id' => $follow->followed_id,
                    'created_at' => $follow->created_at
                ])
        ];
    }
}
ログイン後にコピー

whereInstanceOf

コレクションのタイプベースのフィルタリングを簡素化するため、コードをシンプルで読みやすくしながら、混合オブジェクトタイプの処理が容易になります。

以上がwhere instanceのタイプごとに収集オブジェクトをフィルタリングしますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート