easyswoole集成ORM数据库操作

  • 上篇文章已经接入模板引擎

  • 这篇继续进行数据库的接入

  • ORM拓展引入

composer require easyswoole/orm

  • 我们在dev.php 配置文件中,加入以下配置信息
'MYSQL'  => [
    'host'          => '',
    'port'          => 3300,
    'user'          => '',
    'password'      => '',
    'database'      => '',
    'timeout'       => 5,
    'charset'       => 'utf8mb4',
]
  • EasySwooleEvent.php文件中进行连接注册
 public static function initialize()
    {
     
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');
        $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));
        $config->setMaxObjectNum(20);
        DbManager::getInstance()->addConnection(new Connection($config));
    }
  • 模型创建,app目录下创建Models文件夹,Test.php
namespace App\Models;


use EasySwoole\ORM\AbstractModel;

class Test extends AbstractModel
{
     
    protected $tableName = 'test';//表名

}
  • 控制器中进行查询
     public function index()
    {
     
        $test = Test::create()->where('test',22)->all();
        $model = new Test();
        $model->test = 77;
        $model->yy = 77;
        $model->save();//新增
        Test::create()->update(['test'=>22],['id'=>1]);//更新
        $tt = Test::create()->get(2);
        $tt->test= 55;
        $tt->update();//更新
        Test::create()->destroy(['test'=>77]);//删除
        $this->response()->write(Render::getInstance()->render('index',compact('test')));
    }

  • 模板渲染
 <html>
    <table>
        <thead>
        <tr>
            <th>test</th>
            <th>yy</th>
        </tr>
        </thead>
        <tbody>
        @foreach($test as $tt)
            <tr>
                <td>{
     {
     $tt->test}}</td>
                <td>{
     {
     $tt->yy}}</td>
            </tr>
        @endforeach
        </tbody>
    </table>
</html>

easyswoole集成ORM数据库操作_第1张图片

你可能感兴趣的:(easyswoole,数据库)