将一个DBIO的结果传递给另一个DBIO

时间:2017-08-23 11:28:13

标签: scala playframework slick

我是Slick的新手,我正在尝试重写以下两个查询以在一个事务中工作。我的目标是  1.检查元素是否存在  2.返回现有元素或创建它处理来自MySQL的自动增量

这两个功能是:

<?php
        //Extending the base controller
        class Auth extends CI_Controller{


       //calling the login view
       public function login(){
       //Only username and password credentials are needed here
        $this->form_validation->set_rules('username','Username','required');//using form_validation library
      $this->form_validation->set_rules('password','Password','required|min_length[5]');

      if($this->form_validation->run() == TRUE){

        $username = $_POST['username'];
        $password = md5($_POST['password']);//password hashing

        //Search for user in db
        $this->db->select('*');//query
        $this->db->from('users');
        $this->db->where(array('username' =>$username, 'password' => $password));
        $query = $this->db->get();//store in a var called query
        $user = $query->row();

        if($user->email){
          //temp message
          $this->session->set_flashdata("success","You are now logged in");

          //session variables
           $_SESSION['user_logged'] = TRUE;
           $_SESSION['username'] = $user->username;
           $_SESSION['email'] = $user->email;
           $_SESSION['password'] = $user->email;

           //redirect to their own profile page
           redirect("user/profile", "refresh");
        }else{
          $this->session->set_flashdata("error","No account exists, why not register with us?");
          redirect("auth/login", "refresh");

        }
      }
      $this->load->view('login');
    }

如何安全地链接它们,即。运行第一次检查是否存在,如果对象已经存在则返回,如果它不存在则创建它并在一个事务中返回新元素?

2 个答案:

答案 0 :(得分:3)

您可以使用for comprehension:

def findOrCreate(email: String) = {
  (for {
    found <- findEmail(email)
    em <- found match {
      case Some(e) => DBIO.successful(e)
      case None => createEmail(email)
    }
  } yield em).transactionally
}

val result = db.run(findOrCreate("batman@gotham.gov"))
// Future[Email]

答案 1 :(得分:1)

在猫库的帮助下:

def findOrCreate(email: String): DBIO[Email] = {
    OptionT(findEmail(email)).getOrElseF(createEmail(email)).transactionally
}