Hi, guys! Thank you for your replies!
Really, I been confused with my issue for 2 last days and I’ve found the solution.
I am happy!
I read amazing article "Filtering and sorting by calculated/related fields in Yii 2.0"; You can google it.
Now my code looks like this and this is perfectly works:
Model
-
I added to the rules() construction [[‘minWidth’], ‘safe’]
-
I made getter for minimal width of model getMinWidth()
class Model extends \yii\db\ActiveRecord
/**
* @inheritdoc
*/
public static function tableName()
{
return 'model';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['description', 'is_popular'], 'string'],
[['min_width', 'max_width'], 'integer'],
[['min_price', 'max_price'], 'number'],
[['name'], 'string', 'max' => 45],
[['promo'], 'string', 'max' => 255],
[['img', 'small_img'], 'string', 'max' => 255],
[['minWidth'], 'safe']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'promo' => Yii::t('app', 'Promo'),
'description' => Yii::t('app', 'Description'),
'img' => Yii::t('app', 'Image'),
'small_img' => Yii::t('app', 'Small image'),
'is_popular' => Yii::t('app', 'Is Popular'),
'minWidth' => Yii::t('app', 'Min width'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getComplectations()
{
return $this->hasMany(Complectation::className(), ['model_id' => 'id']);
}
/**
* @return minimal width of model's complectation
*/
public function getMinWidth()
{
$complectations = $this->complectations;
yii\helpers\BaseArrayHelper::multisort($complectations,'width',SORT_ASC);
return $complectations[0]->width;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getImages()
{
return $this->hasMany(Image::className(), ['model_id' => 'id']);
}
}
Controller
When user requests actionIndex, he will receive the gridview with sorting option.
As you told me, I added this construction:
$dataProvider->setSort([
'attributes' => [
'id',
'name',
'minWidth'=>[
'asc' => ['complectation.width' => SORT_ASC],
'desc' => ['complectation.width' => SORT_DESC],
],
]
]);
Then I added join: $query->joinWith([‘complectations’]);
I get this
public function actionIndex()
{
$query = Model::find();
//get data for gridView
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes' => [
'id',
'name',
'minWidth'=>[
'asc' => ['complectation.width' => SORT_ASC],
'desc' => ['complectation.width' => SORT_DESC],
],
]
]);
$query->joinWith(['complectations']);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
My view
<?=GridView::widget([
'dataProvider' => $dataProvider,
'tableOptions' => ['class' => 'table'],
'layout' => '{items}',
'options' => ['class' => 'items-list'],
'columns' => [
'id',
'name',
'minWidth',
['class' => 'yii\grid\ActionColumn'],
],
]);?>