Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to display differnt field other than id when using Associations and baking cake
    text
    copied!<p>I'm using <a href="http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html" rel="nofollow">Associations to Link Models</a> together in CakePHP.</p> <p>I have a <code>Player</code> model that is linked to a <code>Statistic</code> model using a <code>$hasMany</code> relationship. So basically one player can have many statistics.</p> <p>After I set up these relationships, I use <code>cake bake</code> to generate the controllers and views for both the <code>Player</code> and <code>Statistic</code> models.</p> <p>Everything works fine and works as expected, but when I go to add a statistic using the add template, the <code>player_id</code> is used as the association.</p> <p>My question is how do I set up the model to use the <code>player_id</code> as the association but use something like the player's first and last name as the drop down menu in the add template.</p> <p>Currently if I go to add a new statistic, I get a drop down box that called "Player" that lists all of the player id's but what I want is for the player's first_name and last_name to be in that drop down box instead of the id. I realize that I can modify the controller or template to accomplish this, but I Want to know if I can do this while setting up the model so that <code>cake bake</code> can take care of it.</p> <p>Player Model:</p> <pre><code>&lt;?php class Player extends AppModel { public $name = 'Player'; public $belongsTo = array( 'School' =&gt; array( 'className' =&gt; 'School', 'foreignKey' =&gt; 'school_id' ) ); public $hasMany = 'Statistic'; } </code></pre> <p>Statistic Model:</p> <pre><code>&lt;?php class Statistic extends AppModel { public $name = 'Statistic'; public $belongsTo = array( 'Player' =&gt; array( 'className' =&gt; 'Player', 'foreignKey' =&gt; 'player_id' ) ); } </code></pre> <p>Players Table</p> <pre><code>`id|school_id|first_name|last_name|number|position </code></pre>
 

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