Is there any way to limit n number of contents in yii model any my code is
public function rules()
{
return [
[['id', 'editedby', 'cat_id', 'prod_id', 'parent', 'order', 'status'], 'integer'],
[['name', 'content', 'excerpt', 'date', 'url', 'posttype'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Posts::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params,'');
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'date' => $this->date,
'editedby' => $this->editedby,
'cat_id' => $this->cat_id,
'prod_id' => $this->prod_id,
'parent' => $this->parent,
'order' => $this->order,
'status' => $this->status,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'content', $this->content])
->andFilterWhere(['like', 'excerpt', $this->excerpt])
->andFilterWhere(['like', 'url', $this->url])
->andFilterWhere(['like', 'posttype', $this->posttype]);
return $dataProvider;
}
it was a model to list products if the user was in free plan have to show only one product or else have to display products based on plan count will change i have no idea that how to add the condition i need something like
if($user_type==1){
$query->andFilterWhere([['id' => SORT_DESC])->one();]);
}
As Raul Sauco already mentioned you could use something like that
$query->andFilterWhere([['id' => SORT_DESC])->limit($user_type == 1 ? 1 : 20);
Related
I want to get limited numbers of data from database using Yİİ2. I fetched all the record by writing this:
$departures = ArrayHelper::map(
TourDeparture::find()->all(),
'id',
'tour_id'
);
I tried to use limit(5), so that I can get only 5 rows. But I could not. Still, I get the all the rows in the table. How can I achieve that?
Updated: Here is my tourdeparture model
class TourDeparture extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'tour_departure';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['tour_id', 'start_date', 'end_date', 'price_1adult', 'price_2adult', 'price_3adult', 'price_child', 'price_baby', 'min_guests', 'max_guests', 'status', 'required_min_guest'], 'required'],
[['tour_id', 'min_guests', 'max_guests', 'status', 'required_min_guest'], 'integer'],
[['start_date', 'end_date'], 'safe'],
[['price_1adult', 'price_2adult', 'price_3adult', 'price_child', 'price_baby'], 'number'],
[['tour_id'], 'exist', 'skipOnError' => true, 'targetClass' => Tour::className(), 'targetAttribute' => ['tour_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'tour_id' => 'Tour ID',
'start_date' => 'Start Date',
'end_date' => 'End Date',
'price_1adult' => 'Price 1adult',
'price_2adult' => 'Price 2adult',
'price_3adult' => 'Price 3adult',
'price_child' => 'Price Child',
'price_baby' => 'Price Baby',
'min_guests' => 'Min Guests',
'max_guests' => 'Max Guests',
'status' => 'Status',
'required_min_guest' => 'Required Min Guest',
];
}
/**
* Gets query for [[Tour]].
*
* #return \yii\db\ActiveQuery
*/
public function getTour()
{
return $this->hasOne(Tour::className(), ['id' => 'tour_id']);
}
/**
* Gets query for [[TourReservations]].
*
* #return \yii\db\ActiveQuery
*/
public function getTourReservations()
{
return $this->hasMany(TourReservation::className(), ['tour_departure_id' => 'id']);
}
}
$departures = ArrayHelper::map( TourDeparture::find()->limit(5), 'id',
'tour_id' );
I wrote it like above. but ı got all the record
I'm surprised your code worked at all! You are passing the Query class into the map function. ArrayHelper::map is expecting an array and needs the query to be executed using the ->all(). ->limit(5) just adds a new term to the SQL query.
$departures = ArrayHelper::map( TourDeparture::find()->limit(5)->all(), 'id', 'tour_id' );
for retrieve the first 5 rows should be
TourDeparture::find()->orderBy("id")->limit(5)->all()
The code you shared didn't do the limit(5). Anyway, I believe it is caused by the array map,
you may try to simulate the changes as below
$q = TourDeparture::find()->select(['id', 'tour_id'])->limit(5)->asArray()->all();
\yii\helpers\VarDumper::dump($q, $depth = 10, $highlight = true);
For the above, records selected in array form, before array map.
After array map, from here you can compare the changes.
$departures = ArrayHelper::map(
$q,
'id',
'tour_id'
);
\yii\helpers\VarDumper::dump($departures, $depth = 10, $highlight = true);
I've an gridView for showing data. GridView table has a column that called as Created By, this column contain the ID of User that I get from user table. Basicly, this column will show data as Integer(ID) like this:
But I've set code like this to show the username of the ID:
[
'attribute' => 'created_by',
'format' => 'raw',
'value' => function ($data) {
$modelUser = Users::find()->where(['id' => $data->created_by])->one();
$nama = $modelUser->username;
return $nama;
},
'vAlign' => 'middle',
'hAlign' => 'center',
],
Result:
The gridView has filter column, I'm trying to filter data based on inserted value. I'm trying input username as the value for filtering but it give an error message "created By must be an Integer", like this:
How do I can filtering that column using the a username(varchar)?
Thanks
Update
This is my searchModel.php
<?php
namespace app\search;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Product;
/**
* ProductSearch represents the model behind the search form of `app\models\Product`.
*/
class ProductSearch extends Product {
/**
* #inheritdoc
*/
public function rules() {
return [
[['productId', 'userId', 'parentId', 'created_by'], 'integer'],
[['date', 'created_at', 'name', 'address'], 'safe'],
[['price'], 'number'],
];
}
/**
* #inheritdoc
*/
public function scenarios() {
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params) {
$query = Product::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'productId' => $this->productId,
'price' => $this->price,
'created_at' => $this->created_at,
'created_by' => $this->created_by,
]);
$query->andFilterWhere(['MONTH(date)' => $this->date])
->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'address', $this->address]);
return $dataProvider;
}
}
public function rules()
{
return [
[['productId', 'userId', 'parentId'], 'integer'],
[['date', 'created_at', 'name', 'address'], 'safe'],
[['price'], 'number'],
[['created_by'], 'string'],
];
}
public function search($params)
{
$query = Product::find()->joinWith('createdBy'); // Whatever relation name
.
.
.
.
.
// grid filtering conditions
$query->andFilterWhere([
'productId' => $this->productId,
'price' => $this->price,
'created_at' => $this->created_at,
]);
$query->andFilterWhere(['MONTH(date)' => $this->date])
->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'address', $this->address])
->andFilterWhere(['like', 'userTableName.username', $this->created_by]); // Whatever table name and field name.
return $dataProvider;
}
You should add a proper filter to your column
[
'attribute'=>'your_attribute',
......
'filter'=>ArrayHelper::map(YourModel::find()->asArray()->all(),
'your_id_column', 'your_name_column'),
],
In my user table I have fields like firstname and lastname.
then I generated a views using Gii.In my index page now I have Firstname,Lastname,Username etc....
I concatenated my fistname and lastname as Name.
[
'attribute'=>'firstname',
'label' => 'Name',
'format' => 'raw',
'value' => function ($data) {
return Html::a($data->Name);
},
],
In Model
public function getName()
{
return $this->firstname.' '.$this->lastname;
}
unfortunately I am unable to search the name field with last name...
I need to filter the field with both firstname and lastname.
Can anyone please help me....
Thanks in advance.
This is how you setup search model (I did not include your other columns, so dont forget on those)
You can find more here: http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/
class UserSearch extends User
{
public $name;
public function rules()
{
return [
[['name'], 'safe'],
// some other rules ...
];
}
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
public function search($params)
{
$query = User::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['name'] = [
'asc' => ['lastname' => SORT_ASC, 'firstname' => SORT_ASC],
'desc' => ['lastname' => SORT_DESC, 'firstname' => SORT_DESC],
'label' => 'Name',
'default' => SORT_ASC
];
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
// some other filters ...
$query->andFilterWhere([
'or',
['like', 'lastname', $this->name],
['like', 'firstname', $this->name],
]);
return $dataProvider;
}
}
And in your gridview instead of
[
'attribute'=>'firstname',
// ...
],
just use
[
'attribute'=>'name',
],
I have a table that have a relation like this :
Now i get a problem coz if you see,
My work in table in deal_komisi.
But in my searchModel, I want my user can search based in table : item_Layanan.nama_item
This is My model
class DealKomisi extends \yii\db\ActiveRecord {
...... //Common code
/* Related to list_harga */
/**
* #return \yii\db\ActiveQuery
*/
public function getListHarga() {
return $this->hasOne(ListHarga::className(), ['id' => 'list_harga_id']);
}
So, in my DealKomisiSearch, I just use this :
public function search($params) {
$query = DealKomisi::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'list_harga_id' => $this->list_harga_id,
'komisi' => $this->komisi,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);
$query->joinWith('listHarga');
$query->andFilterWhere(['like', 'created_by', $this->created_by])
->andFilterWhere(['like', 'updated_by', $this->updated_by])
;
return $dataProvider;
}
What Should I do, P.S
I also created the list_harga model which is, the relation to **item_layanan ** is definite like this.
class ListHarga extends \yii\db\ActiveRecord
public function getItemLayanan()
{
return $this->hasOne(ItemLayanan::className(), ['id' => 'item_layanan_id']);
}
Please advise.
Any help it so appreciated
I have two collections - Users and Order
I have a list of orders(OrderSearch model) with some users details(email, name..). Now I want to search user details relationally.
OrderSearch Model---
public function search($params)
{
// Email getting from query params
if(!empty($params['email'])){
$this->email = $params['email'];
}
$query = Order::find();
$query->with(['user']); // for related document
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pagesize' => 10,
],
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => isset($this->id)?(int)$this->id:$this->id,
'status' => $this->status,
'user_id' => $this->user_id,
]);
$query->andFilterWhere(['like', 'sku', $this->sku])
->andFilterWhere(['like', 'message', $this->message])
// Tried below code but it is not working.
->andFilterWhere(['like', 'user.email', $this->email]); // $this->email is email which I want to search
return $dataProvider;
}
Relation in Order Model -
public function getUser(){
return $this->hasOne(User::className(), ['_id' => 'user_id']);
}