模型(Models)

1. 创建模型

调试错误:

$messages = $this->getMessages();
    foreach ($messages as $message) {
    echo $message.'\n';
}
$robot       = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
if ($robot->save() == false) {
    echo "Umh, We can't store robots right now: \n";
    foreach ($robot->getMessages() as $message) {
        echo $message, "\n";
    }
} else {
    echo "Great, a new robot was saved successfully!";
}
示冽
public function gettest(){
        $uid= 4023;
        $time =  date('Y-m-d',time());
        $start = strtotime($time.' 00:00:00');
        $conditions = "  earnings_user = :earnings_user: AND add_subtract != :add_subtract: AND add_time >= :add_time: ";
        $bind = ['earnings_user' => $uid,'add_subtract'=>'1', 'add_time' => $start];
        $objQun = $this->SUM([
            "column" => "earnings_bxc",
            "conditions" => $conditions,
            "bind" => $bind,

        ]);
        return $objQun;
        /**
        echo $this->di->get('profiler')->getLastProfile()->getSQLStatement();exit;
        if($objQun){
            $returnData = $objQun->toArray();
            return $returnData;
        }else{
            return false;
        }
         */

    }
<?php
use Phalcon\Mvc\Model;
class Robots extends Model
{

}

默认情况下,模型 “Robots” 对应的是数据库表 “robots”, 如果想映射到其他数据库表,可以使用 getSource() 方法:

<?php
use Phalcon\Mvc\Model;
class Robots extends Model
{
    public function getSource()
    {
        return "the_robots";
    }
}

模型 Robots 现在映射到了 “the_robots” 表。initialize() 方法可以帮助在模型中建立自定义行为,例如指定不同的数据库表。 initialize() 方法在请求期间只被调用一次。

public function initialize()
{
    $this->setSource("news_data");
    $this->belongsTo('id', 'Apps\Frontend\Models\News', 'id', ['alias' => 'News']);  
}

initialize() 方法在请求期间仅会被调用一次,目的是为应用中所有该模型的实例进行初始化。如果需要为每一个实例在创建的时候单独进行初始化, 可以使用 ‘onConstruct’ 事件:

<?php

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function onConstruct()
    {
        // ...
    }
}

1.1 模型放入命名空间

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasMany('id', 'Store\Toys\RobotsParts', 'robots_id');
    }
}

1.2 CRUD (Create, Read, Update, Delete)

输出sql
echo $this->di->get('profiler')->getLastProfile()->getSQLStatement(); exit;
1.2.1 查询
// Find record with id = 3
$robot = Robots::findFirst(3);
// Prints "Terminator"
echo $robot->name;
1.2.2 查找记录(Finding Records)
<?php

// How many robots are there?
$robots = Robots::find();
echo "There are ", count($robots), "\n";

// How many mechanical robots are there?
$robots = Robots::find("type = 'mechanical'");
echo "There are ", count($robots), "\n";

// Get and print virtual robots ordered by name
$robots = Robots::find(
    array(
        "type = 'virtual'",
        "order" => "name"
    )
);
foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Get first 100 virtual robots ordered by name
$robots = Robots::find(
    array(
        "type = 'virtual'",
        "order" => "name",
        "limit" => 100
    )
);
foreach ($robots as $robot) {
   echo $robot->name, "\n";
}
1.2.3 find() 和 findFirst() 方法都接受关联数组作为查询条件:
public function getDataPage($where,$order="id DESC",$limit=10,$offset=0){
        $objQun = $this->find(array(
            'conditions' => $where,
            "order" => $order,
            "offset" =>$offset,
            "limit" => $limit
        ));
        if($objQun){
            $returnData = $objQun->toArray();
            return $returnData;
        }else{
            return false;
        }
    }
参数描述举例
conditions查询操作的搜索条件。用于提取只有那些满足指定条件的记录。默认情下Phalcon\Mvc\Model 假定第一个参数就是查询条件。 “conditions” => “name LIKE ‘steve%’”
columns只返回指定的字段,而不是模型所有的字段。 当用这个选项时,返回的是一个不完整的对象。 “columns” => “id, name”
bindParams绑定与选项一起使用,通过替换占位符以及转义字段值从而增加安全性。 “bind” => array(“status” => “A”, “type” => “some-time”)
bindTypes当绑定参数时,可以使用这个参数为绑定参数定义额外的类型限制从而更加增强安全性。 “bindTypes” => array(Column::BIND_PARAM_STR, Column::BIND_PARAM_INT)
order用于结果排序。使用一个或者多个字段,逗号分隔。 “order” => “name DESC, status”
limit限制查询结果的数量在一定范围内。 “limit” => 10
offsetOffset the results of the query by a certain amount “offset” => 5
group从多条记录中获取数据并且根据一个或多个字段对结果进行分组。 “group” => “name, status”
forUpdate通过这个选项, Phalcon\Mvc\Model 读取最新的可用数据,并且为读到的每条记录设置独占锁。 “for_update” => true
sharedLock通过这个选项, Phalcon\Mvc\Model 读取最新的可用数据,并且为读到的每条记录设置共享锁。 “shared_lock” => true
cache缓存结果集,减少了连续访问数据库。 “cache” => array(“lifetime” => 3600, “key” => “my-find-key”)
hydrationSets the hydration strategy to represent each returned record in the result “hydration” => Resultset::HYDRATE_OBJECTS
1.2.4 除了使用数组作为查询参数外,还可以通过一种面向对象的方式来创建查询:
<?php
$robots = Robots::query()
    ->where("type = :type:")
    ->andWhere("year < 2000")
    ->bind(array("type" => "mechanical"))
    ->order("name")
    ->execute();

静态方法 query() 返回一个对IDE自动完成友好的 Phalcon\Mvc\Model\Criteria 对象。
1.2.5 还有一个 findFirstBy() 方法

这个方法扩展了前面提及的 findFirst() 方法。它允许您利用方法名中的属性名称,通过将要搜索的该字段的内容作为参数传给它,来快速从一个表执行检索操作。
还是用上面用过的 Robots 模型来举例说明:

这里有3个属性:$id, $name$price。因此,我们以想要查询第一个名称为 ‘Terminator’ 的记录为例,可以这样写:

$name  = "Terminator";
$robot = Robots::findFirstByName($name);
if ($robot) {
    $this->flash->success("The first robot with the name " . $name . " cost " . $robot->price ".");
} else {
    $this->flash->error("There were no robots found in our table with the name " . $name ".");
}
请注意我们在方法调用中用的是 ‘Name’,并向它传递了变量 $name$name 的值就是我们想要找的记录的名称。另外注意,当我们的查询找到了符合的记录后,这个记录的其他属性也都是可用的。
1.2.6 将结果集转为数组
$customers = Customers::find();
$arr = $customers->toArray();

$columns = array('id', 'name'); // 需要输出的字段
$rename = true; // 字段名是否是映射后的名称
$negate = false;
$arr = $customers->toArray($columns, $rename, $negate);

1.3 聚合运算

1.3.1 累计(Count)
// How many employees are?
$rowcount = Employees::count();

// How many different areas are assigned to employees?
$rowcount = Employees::count(
    array(
        "distinct" => "area"
    )
);

// How many employees are in the Testing area?
$rowcount = Employees::count(
    "area = 'Testing'"
);

// Count employees grouping results by their area
$group = Employees::count(
    array(
        "group" => "area"
    )
);
foreach ($group as $row) {
   echo "There are ", $row->rowcount, " in ", $row->area;
}

// Count employees grouping by their area and ordering the result by count
$group = Employees::count(
    array(
        "group" => "area",
        "order" => "rowcount"
    )
);

// Avoid SQL injections using bound parameters
$group = Employees::count(
    array(
        "type > ?0",
        "bind" => array($type)
    )
);
1.3.2 累加(Sum)
<?php

// How much are the salaries of all employees?
$total = Employees::sum(
    array(
        "column" => "salary"
    )
);

// How much are the salaries of all employees in the Sales area?
$total = Employees::sum(
    array(
        "column"     => "salary",
        "conditions" => "area = 'Sales'"
    )
);

// Generate a grouping of the salaries of each area
$group = Employees::sum(
    array(
        "column" => "salary",
        "group"  => "area"
    )
);
foreach ($group as $row) {
   echo "The sum of salaries of the ", $row->area, " is ", $row->sumatory;
}

// Generate a grouping of the salaries of each area ordering
// salaries from higher to lower
$group = Employees::sum(
    array(
        "column" => "salary",
        "group"  => "area",
        "order"  => "sumatory DESC"
    )
);

// Avoid SQL injections using bound parameters
$group = Employees::sum(
    array(
        "conditions" => "area > ?0",
        "bind"       => array($area)
    )
);
1.3.3 平均(Average)
// What is the average salary for all employees?
$average = Employees::average(
    array(
        "column" => "salary"
    )
);

// What is the average salary for the Sales's area employees?
$average = Employees::average(
    array(
        "column"     => "salary",
        "conditions" => "area = 'Sales'"
    )
);

// Avoid SQL injections using bound parameters
$average = Employees::average(
    array(
        "column"     => "age",
        "conditions" => "area > ?0",
        "bind"       => array($area)
    )
);
1.3.4 最大/最小(Max/Min)

// What is the oldest age of all employees?
$age = Employees::maximum(
    array(
        "column" => "age"
    )
);

// What is the oldest of employees from the Sales area?
$age = Employees::maximum(
    array(
        "column"     => "age",
        "conditions" => "area = 'Sales'"
    )
);

// What is the lowest salary of all employees?
$salary = Employees::minimum(
    array(
        "column" => "salary"
    )
);

2 修改

一旦记录被加载到内存中之后,你可以修改它的数据并保存所做的修改:

$robot       = Robots::findFirst(3);
$robot->name = "RoboCop";
$robot->save();
$Live = new Live();
1.
$userData = array(
    'id' => $id,
    'content' => $content,
    'status' => $status,
    'created_at' => strtotime($created_at),
    'old_source' => $old_source
);
$a = $Live->doData($userData);

public  function doData($data){

    $result = $this->create($data);
    $insertId = $this->id;
    if ($result === false) {
        /*
        $messages = $this->getMessages();
        foreach ($messages as $message) {
           echo $message.'\n';
        }
       */
        return false;
    } else {
        return $insertId;
    }
}


2. 
$userData = array(
    'id' => $id,
    'content' => $content,
    'status' => $status,
    'created_at' => strtotime($created_at),
    'old_source' => $old_source
);
$a = $Live->create($userData);

3.
$Live->setReadConnectionService('db_two');
$userData = array(
    'content' => $content,
    'status' => $status,
    'created_at' => strtotime($created_at),
    'old_source' => $old_source
);
$Live->id = $id;
$a = $Live->update($userData);

连接别的数据库
$di->set('db_two', function () use ($di) {
    $eventsManager = new Manager();
    // Get a shared instance of the DbProfiler
    $profiler      = $di->getProfiler();
    // Listen all the database events
    $eventsManager->attach('db', function ($event, $connection) use ($profiler) {
        if ($event->getType() == 'beforeQuery') {
            $profiler->startProfile($connection->getSQLStatement());
        }
        if ($event->getType() == 'afterQuery') {
            $profiler->stopProfile();
        }
    });
    $connection = new Mysql(
        array(
            "host" => "121.42.158.222",
            "username" => "root",
            "password" => "7pK1q982Poe",
            "dbname" => "bianjicms",
            'charset'     => 'utf8',
            'port' => '3306'
        ));
    // Assign the eventsManager to the db adapter instance
    $connection->setEventsManager($eventsManager);

    return $connection;
});

3. 打印sql

echo $this->di->get('profiler')->getLastProfile()->getSQLStatement();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值