如何使用 in_array / array_push 获得与自定义 post 相似的 post?

How to use in_array / array_push to get similar posts to a custom post?

我正在使用 array_push 收集与自定义 post 相同的标签 post。我想收集唯一的 post,所以我使用 in_array 来检查 post 的 id。它给了我像 Object of class App\Models\Post could not be converted to int 这样的错误。那么,如何查看数组列表中post的id呢?在 laravel 中还有不使用数组的另一种方法吗?

谢谢。

  foreach ($post->tags as $tag) {

        $tag = Tag::where('name', $tag->name)->first();
        
        $posts = $tag->posts;

        foreach ($posts as $post) {
            
            if (!in_array($post->id, $similar_posts)) {

                array_push($similar_posts, $post);

            }
        }

    }

解法:

我发现由于系统性能和优化代码,使用查询更好。我使用下面的方式而不是上面的方式:

$tags = $post->tags->pluck('id');

$similar_posts = Post::join('post_tag', 'posts.id', 'post_tag.post_id')->whereIn('post_tag.tag_id', $tags)->whereNotIn('posts.id', [$post->id])->select('posts.*')->distinct('posts.id')->get();

它运行良好:)

问题是您的 similar_postsPost 项组成,而您在进行 in_array 调用时正在寻找整数 ID。

所以你能做的就是收集这样的物品$similar_posts[$post->id] = $post。在这种情况下,您既不需要 array_push 也不需要 in_array。这里的问题是为什么你需要收集帖子? $tag->posts 已包含您的帖子。