Skip to content

3.模型

刘广财 edited this page Mar 21, 2018 · 4 revisions

增删改查

1.定义Model

/**
 * 定义用户模型
 */
class UserModel extends \Itxiao6\Database\Eloquent\Model {
    /**
     * 构造方法
     * */
    public function __construct(array $attributes = [])
    {
        # 调用父类方法 
        parent::__construct($attributes);
        // 实例化数据库容器
        $capsule = new \Itxiao6\Database\Capsule\Manager;
        // 添加连接到容器内
        $capsule - >addConnection([
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'dbname',
            'username'  => 'username',
            'password'  => 'pwd',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ]);
        $capsule -> bootEloquent();
    }
    /**
     * 定义表名
     * */
    protected $table = 'users';
}

2.使用模型 具体的 增删改查请参考增删改查

不同的是增删改查里介绍的是用过 \Itxiao6\Database\Capsule\Manager::tale('users') -> get(); 获取模型。 如果使用模型的话 是直接可以 使用 UserModel::get();
    # 查询用户表里的所有数据
    $users = UserModel::get();
    # 查询用户表里id=5的用户
    $users = UserModel::where(['id'=>5]) -> first();
Clone this wiki locally