Smart Relationships
Structure
Migrating
Relationships when the foreign key is accessible
// Model
class Product extends Model
{
public function buyers(): SmartRelationship
{
return $this->smartRelationship(
[
'type' => ['String'],
'reference' => 'customer.id'
]
);
}
...
// routes/web.php
Route::get('forest/product/{id}/relationships/buyers', [ProductsController::class, 'buyers']);
// Controller
class ProductsController extends ForestController
{
public function buyers(int $id): JsonResponse
{
$query = Customer::whereHas('orders.products', fn ($query) => $query->where('products.id', $id))
->paginate($pageParams['size'] ?? null, '*', 'page', $pageParams['number'] ?? null);
return response()->json(
JsonApi::render($query, 'customers', ['count' => $query->total()])
);
}
}
Relationships when you need complex logic to get a foreign key
Last updated