Yii
1
Вклад в тег
/**
* Class VehicleQuery
* @package frontend\modules\v1\models\vehicle
*/
class VehicleQuery extends ActiveQuery
{
public $type;
/**
* @param \yii\db\QueryBuilder $builder
* @return \yii\db\Query
*/
public function prepare($builder)
{
if ($this->type !== null) {
$this->andWhere([Vehicle::tableName() . '.vehicle_type' => $this->type]);
}
return parent::prepare($builder);
}
/**
* Returns popular and active vehicles based on vehicle type
* @return $this
*/
public function popular()
{
$this->andWhere([
Vehicle::tableName() . '.promoted' => 1,
Vehicle::tableName() . '.deleted' => 0,
Vehicle::tableName() . '.status' => '1',
Vehicle::tableName() . '.in_use' => 1
]);
return $this;
}
/**
* @return $this
*/
public function active()
{
$this->andWhere([
Vehicle::tableName() . '.status' => '1',
Vehicle::tableName() . '.deleted' => 0
]);
return $this;
}
/**
* @return $this
*/
public function inUse()
{
$this->andWhere([Vehicle::tableName() . '.in_use' => 1]);
return $this;
}
/**
* Returns most rated vehicles
* @return $this
*/
public function rated()
{
$this->addOrderBy([
Vehicle::tableName() . '.rating' => SORT_DESC,
Vehicle::tableName() . '.created_at' => SORT_DESC
]);
return $this;
}
/**
* Returns most recently vehicles
* @return $this
*/
public function recently()
{
$this->addOrderBy([
Vehicle::tableName() . '.created_at' => SORT_DESC,
Vehicle::tableName() . '.rating' => SORT_DESC
]);
return $this;
}
}
class Vehicle extends ActiveRecord
{
public static function find()
{
return new VehicleQuery(get_called_class());
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCarBrand()
{
return $this->hasOne(CarBrand::className(), ['id' => 'car_brand_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCarGeneration()
{
return $this->hasOne(CarGeneration::className(), ['id' => 'car_generation_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getLanguage()
{
return $this->hasOne(Language::className(), ['id' => 'language_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPosts()
{
return $this->hasMany(Post::className(), ['car_id' => 'id']);
}
}
Vehicle::find()->with(['user', 'posts'])->active()->recently();
public function getActiveUsers()
{
return $this->hasMany(User::className(), ['id' => 'user_id'])
->onCondition(['active' => true]);
}