Retrieving Models
The PHP models provide a fluent syntax for querying the database through the API. In this document, we will demonstrate various methods for retrieving models.
Retrieving a model by id
The model's all
method will retrieve a record with a specific ID.
use SureCart\Models\Product;
$product = Product::find('8ba8d60f-5277-4e6b-807c-dee8166446d5');
Retrieving several models.
The model's all
method will retrieve the first 10 records from the model's associated database table:
use SureCart\Models\Product;
$products = Product::get();
foreach ($products as $product) {
echo $product->name;
}
Building queries
To query by specific parameters, you can use the where
method. This method sends query parameters over the API and returns the matching records.
use SureCart\Models\Product;
$archived_products = Product::where([
'archived' => false
])->get();
Pagination
You can paginate and get subsquent pages of results by using the paginate
method. This method takes 2 parameters, page
and per_page
. The default pagination per_page
limit is 100
.
use SureCart\Models\Product;
$archived_products = Product::where([
'archived' => false
])->paginate([
'per_page' => 20,
'page' => 2
]);
Result:
[
'object' => 'product',
'pagination' => [
'count' => 100,
'limit' => 20,
'page' => 2
],
'data' => [
// 20 products
[
'id' => '8ba8d60f-5277-4e6b-807c-dee8166446d5',
...
]
...
]
]
Refreshing Models
If you already have an instance of a model that was retrieved, you can "refresh" the model using the fresh
method. The fresh
method will re-retrieve the model from the database. The existing model instance will not be affected:
$product = Product::where([
'ids' => [
'8ba8d60f-5277-4e6b-807c-dee8166446d5',
'07fd28e0-e735-4acf-86d8-4d7855055e0b'
]
])->first();
$freshProduct = $product->fresh();
The refresh
method will re-hydrate the existing model using fresh data from the database:
$product = Product::create([
'name' => 'New Product',
]);
$product->name = 'Updated Product';
$product->refresh();
$flight->name; // "New Product"
Updated about 1 year ago