This content is for v3.9. Switch to the latest version for up-to-date documentation.
Querying Models
Understanding how to query your models in Elasticsearch is crucial to leveraging the full potential of this package. This section covers the essentials of model querying, allowing you to fetch and interact with your data efficiently.
Retrieve all records for a given model:
$products = Product::all();
Equivalent to get()
without clauses.
$products = Product::get();
As with Eloquent, you can use the find
method to retrieve a model by its primary key (_id). The method will return a single model instance or null
if no matching model is found.
$product = Product::find('IiLKG38BCOXW3U9a4zcn');
Find the product with _id of IiLKG38BCOXW3U9a4zcn
and return the model collection, or null if it does not exist.
$product = Product::findOrFail('IiLKG38BCOXW3U9a4zcn');
Find the product with _id of IiLKG38BCOXW3U9a4zcn
and return the model collection, or throw a ModelNotFoundException
if no result is found.
As with Eloquent, you can use the first
method to retrieve the first model that matches the query. The method will return a single model instance or null
if no matching model is found.
$product = Product::where('status',1)->first();
Find the first product with a status of 1 and return the model collection if it exists.
$product = Product::where('status',1)->firstOrFail();
Find the first product with a status of 1 and return the model collection, or throw a ModelNotFoundException
if no result is found.
As with Eloquent, you can use the get
method to retrieve all models that match the query. The method will return a model collection or an empty collection if no matching models are found.
$product = Product::where('status',1)->get();
{ "index":"products", "body":{ "query":{ "match":{ "status":1 } }, "_source":[ "*" ] }}