1. Go to this page and download the library: Download vxm/yii2-searchable 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/ */
vxm / yii2-searchable example snippets
use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;
class Article extends ActiveRecord
{
use SearchableTrait;
/**
* @inheritDoc
*/
public function behaviors()
{
return [
'searchable' => SearchableBehavior::class
];
}
}
use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;
class Article extends ActiveRecord
{
use SearchableTrait;
/**
* @inheritDoc
*/
public function behaviors()
{
return [
'searchable' => SearchableBehavior::class
];
}
/**
* Get the index name for the model class.
*
* @return string
*/
public static function searchableIndex(): string
{
return 'articles_index';
}
}
use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;
class Article extends ActiveRecord
{
use SearchableTrait;
/**
* @inheritDoc
*/
public function behaviors()
{
return [
'searchable' => SearchableBehavior::class
];
}
/**
* Get the indexable data array for the model.
*
* @return array
*/
public function toSearchableArray(): array
{
$array = $this->toArray();
// Customize array...
return $array;
}
}
use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;
class Article extends ActiveRecord
{
use SearchableTrait;
/**
* @inheritDoc
*/
public function behaviors()
{
return [
'searchable' => SearchableBehavior::class
];
}
/**
* Get searchable key by default primary key will be use.
*
* @return string key name.
*/
public static function searchableKey(): string
{
return 'id';
}
}
// Deleting via Active Query result...
$models = \app\models\Post::find()->where(['author_id' => 1])->all();
\app\models\Post::deleteSearchable($models);
\app\models\Post::withoutSyncingToSearch(function () {
$post = \app\models\Post::findOne(1);
$post->save(); // will not syncing with index data
});
use vxm\searchable\SearchableBehavior;
use vxm\searchable\SearchableTrait;
class Article extends ActiveRecord
{
use SearchableTrait;
/**
* @inheritDoc
*/
public function behaviors()
{
return [
'searchable' => SearchableBehavior::class
];
}
/**
* Determine if the model should be searchable.
*
* @return bool
*/
public static function shouldBeSearchable()
{
return $this->is_published;
}
}
// Will respect "shouldBeSearchable"...
$post = \app\models\Post::findOne(1);
$post->save();
// Will override "shouldBeSearchable"...
$post->searchable();
$models = \app\models\Post::find()->where(['author_id' => 1])->all();
\app\models\Post::makeSearchable($models);
$posts = \app\models\Post::search('vxm')->all();
$posts = \app\models\Post::search('vxm')->andWhere(['author_id' => 1])->all();
// not use
$posts = \app\models\Post::search('vxm')->where(['author_id' => 1])->all();