Ricerca…


Osservazioni

AR è perfetto quando devi eliminare, aggiornare o creare uno o più record in sequenza. Il suo supporto degli attributi dirty (salvando solo ciò che è stato realmente cambiato) risulta in istruzioni UPDATE ottimizzate che sollevano il carico dal database in modo significativo e riducono le possibilità di conflitti diversi connessi alla modifica dello stesso record da più persone contemporaneamente.

Se non si dispone di una logica veramente complessa nella propria applicazione e quindi non richiede entità di astrazione, AR è la soluzione migliore per eliminare, aggiornare e creare.

AR è anche OK per query semplici con meno di 100 record per pagina. Non è così performante come lavorare con gli array prodotti da query builder o asArray () ma è più piacevole lavorare con.

AR non è raccomandato per query complesse. Solitamente si tratta di aggregare o trasformare dati, quindi ciò che viene restituito non si adatta comunque al modello AR. In questo caso è preferibile utilizzare il generatore di query.

Lo stesso vale per l'importazione e l'esportazione. Meglio usare il generatore di query a causa di grandi quantità di dati e di query possibilmente complesse.

Trova tutti i record

Post::find()->all();
// SELECT * FROM post

o la stenografia

(Restituisce un'istanza del modello di record attivo da una chiave primaria o una matrice di valori di colonna.)

Post::findAll(condition);

restituisce una matrice di istanze di ActiveRecord.

Trova tutto con condizioni

$model = User::find()
        ->where(['id' => $id])
        ->andWhere('status = :status', [':status' => $status])
        ->all();

Trova tutto con orderBy

$model = User::find()
         ->orderBy(['id'=>SORT_DESC])
        ->all();
Or

$model = User::find()
         ->orderBy(['id'=>SORT_ASC])
        ->all();

Dove la clausola

OPERATORI

$postsGreaterThan = Post::find()->where(['>', 'created_at', '2016-01-25'])->all();
// SELECT * FROM post WHERE created_at > '2016-01-25'

$postsLessThan = Post::find()->where(['<', 'created_at', '2016-01-25'])->all();
// SELECT * FROM post WHERE created_at < '2016-01-25'

$postsNotEqual = Post::find()->where(['<>', 'created_at', '2016-01-25'])->all();
// SELECT * FROM post WHERE created_at <> '2016-01-25'

NEL

$postsInArray = Post::find()->where(['id' => [1,2,3]])->all();
// SELECT * FROM post WHERE id IN (1,2,3)

FRA

$postsInBetween = Post::find()
->where(['between', 'date', "2015-06-21", "2015-06-27" ])
->all();

NULLO

$postsWithNullTitle = Post::find()->where(['title' => null]);
// SELECT * FROM post WHERE title IS NULL

E

$postsAND = Post::find()->where(['title' => null, 'body' => null]);
// SELECT * FROM post WHERE title IS NULL AND body IS NULL

O

$postsAND = Post::find()->where(['OR', 'title IS NULL', 'body IS NULL']);
// SELECT * FROM post WHERE title IS NULL OR body IS NULL

NON

 $postsNotEqual = Post::find()->where(['NOT', ['created_at'=>'2016-01-25']])->all();
// SELECT * FROM post WHERE created_at IS NOT '2016-01-25'

CLIENTI NASCOSTI

$postsNestedWhere = Post::find()->andWhere([
    'or',
    ['title' => null],
    ['body' => null]
])->orWhere([
    'and',
    ['not', ['title' => null]],
    ['body' => null]
]);
// SELECT * FROM post WHERE (title IS NULL OR body IS NULL) OR (title IS NOT NULL AND body IS NULL)

LIKE OPERATOR con filterWhere metodi activerecord

Ad esempio, nel filtro di ricerca si desidera filtrare il post bruciando il titolo del post o la descrizione postata dall'utente attualmente connesso.

$title = 'test';
$description = 'test';

i) andFilterWhere ()

$postLIKE = Post::find()->where(['user_id' => Yii::$app->user->getId()])->andfilterWhere(['or', ['title' => $title, 'description' => $description]])->all();
//SELECT * FROM post WHERE user_id = 2 AND ((`title` LIKE '%test%') OR (`description` LIKE '%test%'))

ii) oFilterWhere ()

$postLIKE = Post::find()->where(['user_id' => Yii::$app->user->getId()])->orFilterWhere(['or', ['title' => $title, 'description' => $description]])->all();
//SELECT * FROM post WHERE user_id = 2 OR ((`title` LIKE '%test%') OR (`description` LIKE '%test%'))

iii) filterWhere ()

$postLIKE = Post::find()->filterWhere(['AND', ['title' => $title, 'description' => $description]])->andWhere(['user_id' => Yii::$app->user->getId()])->all();
//SELECT * FROM post WHERE ((`title` LIKE '%test%') AND (`description` LIKE '%test%')) AND user_id = 2

Nota: durante l'utilizzo di filterWhere () dobbiamo chiamare all andwhere () o oWhere () dopo filterWhere () altrimenti tutte le condizioni verranno rimosse tranne filterWhere ()

Crea una classe ActiveRecord con valore dei campi basati sugli eventi

    <?php
    namespace models;

    use yii\db\ActiveRecord;
    use yii\behaviors\TimestampBehavior;

    class Post extends ActiveRecord
    {
        public static function tableName()
        {
            return 'post';
        }

        public function rules() {
            return [
                [['created_at', 'updated_at'], 'safe'],
            ];
        }
        public function behaviors() {
            parent::behaviors();
    
            return [
              'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                  ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                  ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at']
                ],
                'value' => date('Y-m-d H:i:s'),
              ]
            ];
          }
    }

O questo può essere usato

public function beforeSave($insert)
{
    if($this->isNewRecord){
        //When create    
    }else{
         //When update
    }

    return parent::beforeSave($insert);
}

  public function afterSave($insert, $changedAttributes )
{
    if($insert){
        //When create    
    }else{
         //When update
    }
    return parent::afterSave($insert, $changedAttributes);
}

Trova un record

$customer = Customer::findOne(10);

o

$customer = Customer::find()->where(['id' => 10])->one();

o

$customer = Customer::find()->select('name,age')->where(['id' => 10])->one();

o

$customer = Customer::findOne(['age' => 30, 'status' => 1]);

o

$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();

Trova una query

Trova un singolo record basato su id.

$model = User::findOne($id);

Seleziona una singola colonna in base all'ID.

$model = User::findOne($id)->name;

Recupera il singolo record dal database in base alle condizioni.

$model = User::find()->one();  // give first record

$model = User::find()->where(['id' => 2])->one(); // give single record based on id

Seleziona record di singole colonne dal database in base alle condizioni.

$model = User::find()->select('name,email_id')->where(['id' => 1])->one();

O

$model = User::find()->select(['id','name','email_id'])->where(['id' => 1])->one();

Ordinato da

$model = User::find()->select(['id','name','email_id'])->orderBy(['id' => SORT_DESC])->one();

OR 

$model = User::find()->select(['id','name','email_id'])->orderBy(['id' => SORT_ASC])->one();

Record attivi con sottocategorie

Esempio: clienti che possono creare un post. Ogni cliente può creare più post. Non appena il cliente crea il post, il post sarà sottoposto a revisione da parte degli amministratori. Ora dobbiamo recuperare l'elenco dei clienti che hanno tutti i post attivi utilizzando la sotto-query.

Nota: se un cliente ha 5 post, tra 5 post se ha almeno uno inattivo, dobbiamo escludere questo cliente dall'elenco dei clienti.

$subQuery = Post::find()->select(['customer_id'])->where(['status' => 2]); //fetch the customers whos posts are inactive - subquery
$query = Customer::find()->where(['NOT IN', 'id', $subQuery])->all(); //Exclude the customers whos posts are inactive by using subquery


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow