Help us understand the problem. What is going on with this article?

Cakephpでユーザー登録後、登録したユーザーのIDを更新ID、新規登録IDに入れる

More than 5 years have passed since last update.

前提条件

  • ログインしていないユーザーがユーザ新規登録できる
  • ログイン認証にAuthComponentを使用
  • 登録時、ログインユーザのidを各テーブルのcreated_id, modified_idにセットしている

実装

ログインしていない状態でユーザを新規登録した場合、created_id,modified_idにはidがセットされません。
なので、afterSaveメソッドにIDをセットする処理を追加しました。
ログイン時はログインIDが、未ログインは新規登録した際発行されたIDがセットされます。

    function afterSave($created)  
    {  
      if ($created) {
        App::uses('AuthComponent',  'Controller/Component');
        $user = AuthComponent::user();
        if(empty($user)){
            $id = $this->data[$this->alias]["id"];
        }else{
            $id = $user['id'];
        }
        $data[$this->alias]["id"] = $id;
        $data[$this->alias]["created_id"] = $id;       
        $data[$this->alias]["modified_id"] = $id;       
        $this->save($data, array('callbacks' => false));
      }
    }

ポイントは、callbacs => false です。
これがないとbeforeSave(), afterSave()が動いてしまい、余計な処理が走ってしまいます。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした