1. 程式人生 > >yii2 框架的 AR 和 DAO 增刪改查

yii2 框架的 AR 和 DAO 增刪改查

寫法 mod sar 增刪改查 title isn function rec 自己

自己做個總結 方便以後查找使用

/**
* yii 的增刪改查
*/
//增
public function add1($data)
{
$data = [
‘title‘=>$data[‘YiiNews‘][‘title‘],
‘msg‘=>$data[‘YiiNews‘][‘msg‘],
‘img‘=>$data[‘News‘][‘img‘],
];
$this->setAttributes($data) ;
return $this->insert();
}

public function add2($data)
{
$this->setAttributes($data);
$this->isNewRecord = true;
$this->id = 0;
return $this->save(0);
}

public function add3($data)
{
$sql = "insert into yii_news (title,msg) values (‘{$data[‘title‘]}‘,‘{$data[‘msg‘]}‘)";
return \yii::$app->db->createCommand($sql)->execute();
}

//刪
public function del1($id)
{
$this->deleteAll(‘id = ‘.$id);//作死寫法 不要這麽寫
$this->deleteAll([‘id‘=>$id]);
}

public function del2($id)
{
$sql = "delete from yii_news where id = ‘$id‘";
return \yii::$app->db->createCommand($sql)->execute();
}

//改
public function save1($data)
{
return $this->updateAll($data,[‘id‘=> 1]);
}

//查
public function sel1()
{
return $this->find()->where("title = ‘title11‘")->andWhere("id > 0")->asArray(true)->all();
// return $this->find()->select()->where("title = ‘title11‘")->orWhere("id = 9")->asArray(true)->one();
}

public function sel2()
{
$sql = "select * from yii_news ";
return \yii::$app->db->createCommand($sql)->queryAll();
}

更具體歡迎訪問 http://www.php20.com/forum.php?mod=viewthread&tid=158&extra=page%3D1

yii2 框架的 AR 和 DAO 增刪改查