php 基于多个 ID 检索 Laravel 模型结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28509985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve Laravel Model results based on multiple ID's
提问by justinl
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
到我的Laravel
应用程序中。我将它用作我的搜索引擎,用户将在其中输入搜索词,然后ZendSearch
将按相关性排序的结果数组返回给我。但是,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.
接下来是查询我的模型以根据ZendSearch
数组结果检索结果的正确方法,该数组结果只是基于相关性排序的 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.
我知道Model::find(1)
哪个会返回我的 ID 为 1 的记录,但是我如何为该find()
方法提供一个 ID 数组,我想按照我给它的顺序返回这些 ID。
回答by lukasgeiter
That's simple. Use findMany
:
这很简单。使用findMany
:
$models = Model::findMany([1, 2, 3]);
By the way, you can also pass an array to find()
and it will internally call findMany
:
顺便说一句,您还可以将数组传递给find()
它,它会在内部调用findMany
:
$models = Model::find([1, 2, 3]);
Under the hood it just does a whereIn
so you could do that too:
在引擎盖下它只是做了一个whereIn
所以你也可以这样做:
$models = Model::whereIn('id', [1, 2, 3])->get();