基于多个 ID 检索 Laravel 模型结果

我已经在我的 Laravel 应用程序中实现了 ZendSearch.我使用它作为我的搜索引擎,用户将在其中输入一个搜索词,然后 ZendSearch 将返回一个按相关性排序的结果数组.但是,ZendSearch 返回的数组只返回我的记录 ID(它不返回任何实际的记录信息).

I have implemented ZendSearch into my Laravel application. I am using it as my search engine where users will type a search word, and then ZendSearch will return me an array of results ordered by relevance. However, the array that ZendSearch returns, only returns my record ID's (it doesn't return any of the actual record information).

接下来查询我的模型以检索基于 ZendSearch 数组结果的结果的正确方法是什么,该数组结果只是一个基于相关性排序的 ID 数组.

What would next be the correct way to query my Model to retrieve the results based on the ZendSearch array results which is just an array of ID's ordered based on relevance.

我知道 Model::find(1) 会返回我的 ID 为 1 的记录,但是我如何为 find() 方法提供一个数组我希望按照我提供的顺序返回的 ID.

I know of Model::find(1) which would return my record with an ID of 1, but how can I feed that find() method an array of ID's that I want to be returned in the order I am giving it.

推荐答案

这很简单.使用 findMany:

$models = Model::findMany([1, 2, 3]);

顺便说一下,你也可以将一个数组传递给 find(),它会在内部调用 findMany:

By the way, you can also pass an array to find() and it will internally call findMany:

$models = Model::find([1, 2, 3]);

<小时>

在引擎盖下它只是做了一个 whereIn 所以你也可以这样做:


Under the hood it just does a whereIn so you could do that too:

$models = Model::whereIn('id', [1, 2, 3])->get();

相关文章