• Yii操作数据库的3种方法


    一、执行原生太SQL的PDO方式。

    复制代码代码如下:
    $sql = "";//原生态sql语句 
    xx::model()->dbConnection->createCommand($sql)->execute();


    二、Active Record方式 
    (1)New 方式

    复制代码代码如下:
    $post=new Post; 
    $post->title='sample post'; 
    $post->content='post body content'; 
    $post->save();


    (2)Criteria方式 
    也可以使用 $condition 指定更复杂的查询条件。 不使用字符串,我们可以让 $condition 成为一个 CDbCriteria 的实例,它允许我们指定不限于 WHERE 的条件。 

    复制代码代码如下:
    $criteria=new CDbCriteria; 
    $criteria->select='title';  // 只选择 'title' 列 
    $criteria->condition='postID=:postID'; 
    $criteria->params=array(':postID'=>10); 
    $post=Post::model()->find($criteria);


    一种替代 CDbCriteria 的方法是给 find 方法传递一个数组。 数组的键和值各自对应标准(criterion)的属性名和值,上面的例子可以重写为如下: 

    复制代码代码如下:
    $post=Post::model()->find(array( 
        'select'=>'title', 
        'condition'=>'postID=:postID', 
        'params'=>array(':postID'=>10), 
    ));


    当一个查询条件是关于按指定的值匹配几个列时,我们可以使用 findByAttributes()。我们使 $attributes 参数是一个以列名做索引的值的数组。在一些框架中,此任务可以通过调用类似 findByNameAndTitle 的方法实现。虽然此方法看起来很诱人,但它常常引起混淆、冲突和比如列名大小写敏感的问题。 
    三、Query Builder 方式 

    复制代码代码如下:
    $user = Yii::app()->db->createCommand() 
        ->select('id, username, profile') 
        ->from('tbl_user u') 
        ->join('tbl_profile p', 'u.id=p.user_id') 
        ->where('id=:id', array(':id'=>$id)) 
        ->queryRow();
  • 相关阅读:
    day25:接口类和抽象类
    vue1
    How the weather influences your mood?
    机器学习实验方法与原理
    How human activities damage the environment
    Slow food
    Brief Introduction to Esports
    Massive open online course (MOOC)
    Online learning in higher education
    Tensorflow Dataset API
  • 原文地址:https://www.cnblogs.com/xieqian111/p/5765300.html
Copyright © 2020-2023  润新知