Note that there are some explanatory texts on larger screens.

plurals
  1. POCakephp - Adding data to relational database
    text
    copied!<p>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.</p> <p>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:</p> <p>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.</p> <p>Just in case, here's the definitions for both classes in php:</p> <p>For Album:</p> <pre><code>&lt;?php class Album extends AppModel { public $name = 'Album'; public $hasMany = array( 'Image' =&gt; array( 'className' =&gt; 'Image', 'order' =&gt; 'Image.added DESC', 'dependent' =&gt; true ) ); public $validate = array( 'name' =&gt; array( 'rule' =&gt; 'notEmpty' ), 'description' =&gt; array( ) ); } ?&gt; </code></pre> <p>For Image:</p> <pre><code>&lt;?php class Image extends AppModel { public $name = 'Image'; public $belongsTo = 'Album'; } ?&gt; </code></pre> <p>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:</p> <pre><code>public function add() { if ($this-&gt;request-&gt;is('post')) { $this-&gt;Album-&gt;create(); if ($this-&gt;Album-&gt;save($this-&gt;request-&gt;data)) { $this-&gt;Session-&gt;setFlash('Your album has been created.'); $this-&gt;redirect(array('action' =&gt; 'index')); } else { $this-&gt;Session-&gt;setFlash('Unable to create your album.'); } } } </code></pre> <p>Along with a simple function in the view file for the add function:</p> <pre><code>&lt;?php echo $this-&gt;Form-&gt;create('Album'); echo $this-&gt;Form-&gt;input('name'); echo $this-&gt;Form-&gt;input('description'); echo $this-&gt;Form-&gt;end('Save Album'); ?&gt; </code></pre> <p>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?</p> <p>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 :)</p> <p>Thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload