yii2
활성 레코드
수색…
비고
AR은 하나 이상의 레코드를 순차적으로 삭제, 업데이트 또는 생성해야하는 경우에 적합합니다. 더티 속성 (실제 변경된 내용 만 저장)을 지원하면 최적화 된 UPDATE 문을 사용하여 데이터베이스에서로드를 크게 끌어 올리고 동시에 여러 사람이 동일한 레코드를 편집 할 때 발생할 수있는 다양한 충돌 문제를 줄일 수 있습니다.
응용 프로그램에 실제로 복잡한 논리가 없으므로 추상 엔티티가 필요하지 않은 경우 AR이 삭제, 업데이트 및 작성에 가장 적합합니다.
AR은 페이지 당 100 개 미만의 레코드를 생성하는 간단한 쿼리에 대해서도 OK입니다. 쿼리 빌더 또는 asArray ()에 의해 생성 된 배열로 작업하는 것보다 성능이 좋지는 않지만 작업하는 것이 더 즐겁습니다.
복잡한 쿼리에는 AR을 사용하지 않는 것이 좋습니다. 이것은 대개 데이터를 집계하거나 변환하는 것에 대한 것이므로 리턴되는 것은 AR 모델에 어울리지 않습니다. 이 경우에는 쿼리 작성기를 사용하는 것이 좋습니다.
가져 오기 및 내보내기도 동일합니다. 많은 양의 데이터와 복잡한 쿼리 때문에 쿼리 작성기를 사용하는 것이 좋습니다.
모든 레코드 찾기
Post::find()->all();
// SELECT * FROM post
또는 속기
기본 키 또는 열 값 배열을 사용하여 활성 레코드 모델 인스턴스를 반환합니다.
Post::findAll(condition);
ActiveRecord 인스턴스의 배열을 반환합니다.
조건을 모두 사용하여 찾기
$model = User::find()
->where(['id' => $id])
->andWhere('status = :status', [':status' => $status])
->all();
주문과 함께 모두 찾기
$model = User::find()
->orderBy(['id'=>SORT_DESC])
->all();
Or
$model = User::find()
->orderBy(['id'=>SORT_ASC])
->all();
Where 절
운영자
$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'
에서
$postsInArray = Post::find()->where(['id' => [1,2,3]])->all();
// SELECT * FROM post WHERE id IN (1,2,3)
중에서
$postsInBetween = Post::find()
->where(['between', 'date', "2015-06-21", "2015-06-27" ])
->all();
없는
$postsWithNullTitle = Post::find()->where(['title' => null]);
// SELECT * FROM post WHERE title IS NULL
과
$postsAND = Post::find()->where(['title' => null, 'body' => null]);
// SELECT * FROM post WHERE title IS NULL AND body IS NULL
또는
$postsAND = Post::find()->where(['OR', 'title IS NULL', 'body IS NULL']);
// SELECT * FROM post WHERE title IS NULL OR body IS NULL
아니
$postsNotEqual = Post::find()->where(['NOT', ['created_at'=>'2016-01-25']])->all();
// SELECT * FROM post WHERE created_at IS NOT '2016-01-25'
네이티브 클레임
$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 with filterWhererecord 메서드
예를 들어 검색 필터에서 현재 로그인 한 사용자가 게시 한 게시물 제목이나 설명을 숨겨서 게시물을 필터링하려고합니다.
$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) orFilterWhere ()
$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
참고 : filterWhere ()를 사용하는 동안 filterWhere () 다음에 all andwhere () 또는 orWhere ()를 호출해야합니다. 그렇지 않으면 filterWhere ()
이벤트 기반 필드 값을 사용하여 ActiveRecord 클래스 만들기
<?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'),
]
];
}
}
또는 이것을 사용할 수 있습니다.
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);
}
하나의 레코드 찾기
$customer = Customer::findOne(10);
또는
$customer = Customer::find()->where(['id' => 10])->one();
또는
$customer = Customer::find()->select('name,age')->where(['id' => 10])->one();
또는
$customer = Customer::findOne(['age' => 30, 'status' => 1]);
또는
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
하나의 검색어 찾기
id를 기반으로 한 단일 레코드를 찾습니다.
$model = User::findOne($id);
id를 기반으로 단일 열을 선택하십시오.
$model = User::findOne($id)->name;
조건에 따라 데이터베이스에서 단일 레코드를 검색하십시오.
$model = User::find()->one(); // give first record
$model = User::find()->where(['id' => 2])->one(); // give single record based on id
조건에 따라 데이터베이스에서 단일 열 레코드를 선택하십시오.
$model = User::find()->select('name,email_id')->where(['id' => 1])->one();
또는
$model = User::find()->select(['id','name','email_id'])->where(['id' => 1])->one();
주문
$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();
하위 쿼리가있는 활성 레코드
예 : 게시물을 만들 수있는 고객. 각 고객은 여러 게시물을 작성할 수 있습니다. 고객이 게시물을 작성하자마자 게시물은 관리자 검토를받습니다. 이제 하위 쿼리를 사용하여 모든 활성 게시물이있는 고객 목록을 가져와야합니다.
참고 : 고객이 5 개의 게시물을 가지고있는 경우 5 개의 게시물 중 1 개 이상이 비활성 인 경우 해당 고객을 고객 목록에서 제외해야합니다.
$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