PHP code example of needbrainz / scout-typesense-aggregator

1. Go to this page and download the library: Download needbrainz/scout-typesense-aggregator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

needbrainz / scout-typesense-aggregator example snippets




namespace App\Search;

use NeedBrainz\TypesenseAggregator\TypesenseAggregator;

class MyAggregator extends TypesenseAggregator
{
    /**
     * The names of the models that should be aggregated.
     *
     * @var string[]
     */
    protected $models = [
        App\Models\MyModel::class,
        App\Models\MyOtherModel::class,
    ];
}

'typesense' => [
    'model-settings' => [
        MyAggregator::class => [
           'collection-schema' => [
                'fields' => [
                    [
                        'name' => 'id',
                        'type' => 'string',
                    ],
                    // Your aggregated fields
                    [
                        'name' => 'name',
                        'type' => 'string',
                    ],
                    [
                        'name' => 'description',
                        'type' => 'string',
                    ],
                    [
                        'name' => 'created_at',
                        'type' => 'int64',
                    ],
                ],
                'default_sorting_field' => 'created_at',
           ],
           'search-parameters' => [
                'query_by' => 'name,description',
           ]
        ],
    ]

use App\Search\MyAggregator;

public function boot(): void
{
    MyAggregator::bootSearchable();
}

public function toSearchableArray(): array
{
    $array = [
        'id' => (string )$this->getScoutKey(),
        'created_at' => $this->model->created_at->timestamp,
        // default empty values
        'name' => '',
        'description' => '',
    ];

    // Customize the merging of the models here
    if ($this->model instanceof MyModel) {
        $array['name'] = (string) $this->model->name;
        $array['description'] = (string) $this->model->description;
    } elseif ($this->model instanceof MyOtherModel) {
        $array['name'] = (string) $this->model->title;
        $array['description'] = (string) $this->model->summary;
    }

    return $array;
}
bash
php artisan make:typesense-aggregator MyAggregator