Question

I'm currently working on a gallery using CakePHP. This is the first time I use a relational database with Cake and I have a question regarding it.

In my gallery, which is for now a very simple one (Since it is meant as a learning experience that might lead to a final product), I have a single relation set:

First, there are two models: Album and Image. An album is related to an Image by a HasMany relationship and an Image belongs to an album (By a BelongsTo relationship). I have set up the database relation on cakePHP with no problems.

Just in case, here's the definitions for both classes in php:

For Album:

<?php 

class Album extends AppModel {
    public $name = 'Album';

    public $hasMany = array(
        'Image' => array(
            'className' => 'Image',
            'order' => 'Image.added DESC',
            'dependent' => true
        )
    );

    public $validate = array(
        'name' => array(
            'rule' => 'notEmpty'
        ),
        'description' => array(
        )
    );

}

?>

For Image:

<?php 

class Image extends AppModel {
    public $name = 'Image';

    public $belongsTo = 'Album';


}

?>

The Image class still has no validation because I'm starting to work with it. Now, I can add albums very easily with a simple function in the controller page:

public function add() {
    if ($this->request->is('post')) {
        $this->Album->create();
        if ($this->Album->save($this->request->data)) {
            $this->Session->setFlash('Your album has been created.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to create your album.');
        }
    }
}

Along with a simple function in the view file for the add function:

<?php

echo $this->Form->create('Album');
echo $this->Form->input('name');
echo $this->Form->input('description');

echo $this->Form->end('Save Album');
?>

However, I have no clue how to add images. Sure, I could use a code just like the Album one, but how exactly do I set which album the image belongs to? I've searched and found tons of questions regarding how to set up a relation, but none regarding how to actually add relational data to an already set up database. Any help with this?

Note that I'm asking specifically how to put the data into the database following the relational model. I already know how to handle the images themselves with cakephp, it's the whole adding relational data I'm wondering about :)

Thanks in advance!

Was it helpful?

Solution

to create a select:

in your ImagesController

public function add() {
    //
    // ...
    //
    $albums = $this->Image->Album->find('list');
    $this->set('albums', $albums);
}

somewhere in your add.ctp view file

echo $this->Form->input('album_id');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top