开发者

Adding profile image in cakephp

I currently, have 2 database. images & users.

In my user Model I have:

    var $belongsTo=array(
    'Image'=>array('className'=>'Image')
);

In my image Model I have:

    var $hasOne =array(
    'Users'=>array('className'=>'User')
);

I want to achieve the following below: My users database has a field 'image_id' and it is linked to my images database field 'id'. Example: images database id = 1 users database image_id = 1

Below is the code for the add function in my image_controller. I want to add a particular image and I want the images 'id' to be save to t开发者_高级运维he users database 'image_id'. How do I achieve this?

    function add() {
    $this->layout = "mainLayout";      
    if (!empty($this->data)) {
        $this->Image->create();

        if ($this->Image->save($this->data)) {

            $user_id = $this->User->getUserInfo($this->Auth->user('id'));
            $this->data['User']['image_id'] = $user_id;

            $this->Session->setFlash('The image has been saved', true);
            $this->redirect(array('controller' => 'Users', 'action' => 'profile'));
        } else {
            $this->Session->setFlash('The image could not be saved. Please, try again.', true);
        }
    }

    $current_user_pic =$this->User->getUserInfo($this->Auth->user('id'));
    $this->set(compact('current_user_pic')); 
}


make it User hasOne Image (Image hasOne User is just semantically weird). So when you save an image record, just set the 'user_id' to $this->Auth->user('id')) before saving.

Also, don't use var $uses = array('User','Image'); When you already set the relationship, you can access Image model through User model: $this->User->Image->save($this->data)

Edit: Ok, so remove the image_id field in users table, add user_id field to images table. If you use bake command to generate code, you might want to save your code in the models, controllers, and views for users and images, then re-bake these 2. Declare relationships: User hasOne Image and Image belongsTo User (I assume you know how to do that).

When you save the image, set $this->data['Image']['user_id'] = $this->Auth->user('id') before $this->User->Image->save($this->data)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜