<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
romanzipp / laravel-projectable-aggregates example snippets
new class() extends Migration
{
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('project_doors_count')->default(0);
});
}
}
use romanzipp\ProjectableAggregates\Attributes\ConsumesProjectableAggregate;
use romanzipp\ProjectableAggregates\ProjectionAggregateType;
class Car extends Model
{
#[ConsumesProjectableAggregate(
projectionAttribute: 'project_doors_count', // <- Name of the projection field in the database
projectionType: ProjectionAggregateType::TYPE_COUNT
)]
public function doors(): HasMany
{
return $this->hasMany(Door::class);
}
}
use romanzipp\ProjectableAggregates\Attributes\ProvidesProjectableAggregate;
use romanzipp\ProjectableAggregates\ProjectionAggregateType;
class Door extends Model
{
#[ProvidesProjectableAggregate(
projectionAttribute: 'project_doors_count', // <- Name of the FOREIGN projection field in the database
projectionType: ProjectionAggregateType::TYPE_COUNT
)]
public function car(): BelongsTo
{
return $this->belongsTo(Car::class);
}
}
use romanzipp\ProjectableAggregates\ProjectableAggregateRegistry;
class AppServiceProvider extends ServiceProvider
{
public function boot(ProjectableAggregateRegistry $registry)
{
$registry->registerConsumers([
Car::class,
]);
$registry->registerProviders([
Door::class,
]);
}
}
> #[ProvidesProjectableAggregate(
> projectionAttribute: 'project_price_average',
> projectionType: ProjectionAggregateType::TYPE_AVG,
> targetAttribute: 'price', // <- Attribute of the related model to average/sum up
> )]
>