{ES} - 3.7.6.2 hasOne

Configuremos un modelo Usuario con una relación hasOne con un modelo Perfil.

Primero, necesitas establecer las claves de tus tablas de base de datos correctamente. Para que funcione una relación hasOne correctamente, una tabla ha de contener una clave foránea que apunte a un registro en la otra. En este caso, la tabla 'perfiles' contendrá un campo llamado usuario_id. El patrón básico es:

hasOne: el otro modelo contiene la clave foránea.
Relación Esquema
Manzana hasOne Plátano plananos.manzana_id
Usuario hasOne Perfil perfiles.usuario_id
Doctor hasOne Mentor mentores.doctor_id

El archivo del modelo Usuario será grabado en /app/models/usuario.php. Para definir la asociación 'Usuario hasOne Perfil', añade la propiedad $hasOne a la clase del modelo. Recuerda tener un modelo Perfil en /app/models/perfil.php, o la asociación no funcionará.

<?php
class Usuario extends AppModel {
    var $name = 'Usuario';
    var $hasOne = 'Perfil';   
}
?>
  1. <?php
  2. class Usuario extends AppModel {
  3. var $name = 'Usuario';
  4. var $hasOne = 'Perfil';
  5. }
  6. ?>

Hay dos manera de describir esta relación en tus archivos del modelo. La manera más simple es establecer el atributo $hasOne a una cadena de caracteres conteniendo el nombre de la clase del modelo asociado, como hemos hecho arriba.

Si necesitas más control, puedes definir tus asociaciones utilizando sintaxis de arrays. Por ejemplo, podrías desear limitar la asociación para incluir sólo ciertos registros.

<?php
class Usuario extends AppModel {
    var $name = 'Usuario';          
    var $hasOne = array(
        'Perfil' => array(
            'className'    => 'Perfil',
            'conditions'   => array('Perfil.publicado' => '1'),
            'dependent'    => true
        )
    );    
}
?>
  1. <?php
  2. class Usuario extends AppModel {
  3. var $name = 'Usuario';
  4. var $hasOne = array(
  5. 'Perfil' => array(
  6. 'className' => 'Perfil',
  7. 'conditions' => array('Perfil.publicado' => '1'),
  8. 'dependent' => true
  9. )
  10. );
  11. }
  12. ?>

Las claves posibles para los arrays de asociaciones hasOne incluyen:

  • className: el nombre de la clase del modelo que está siendo asociado al modelo actual. si estás definiendo una relación 'Usuario hasOne Perfil', la clave className debería ser igual a 'Perfil'.
  • foreignKey: el nombre de la clave foránea que se encuentra en el otro modelo. Esto es especialmente útil si necesitas definir múltiples relaciones hasOne. El valor por defecto para esta clave es el nombre en singular del modelo actual, seguido del sufijo '_id'. En el ejemplo de arriba, debería ser por defecto 'usuario_id'.
  • conditions: Un fragmento SQL usado para filtrar registros del modelo relacionado. Es buena práctica usar nombres de modelos en los fragmentos SQL: 'Perfil.aprobado = 1' siempre es mejor que simplemente 'aprobado = 1'.
  • fields: Una lista de campos a ser devueltos cuando se traen los datos del modelo asociado. Por defecto devuelve todos los campos.
  • dependent: Cuando la clave dependent se establece a true, y el método delete() del modelo es llamado con el parámetro $cascada con valor true, los registros del modelo asociado también son borrados. En este caso lo ponemos a true de manera que borrando un Usuario también borrará su Perfil asociado.

Una vez que esta asociación ha sido definida, las operaciones de búsqueda en el modelo usuario traerán también el registro Perfil relacionado si existe:

// Resultados de ejemplo de una llamada a $this->Usuario->find()
Array
(
    [Usuario] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    [Perfil] => Array
        (
            [id] => 12
            [user_id] => 121
            [habilidad] => Hornear Pasteles
            [created] => 2007-05-01 10:31:01
        )
)

{EN} - 3.7.6.2 hasOne

Let’s set up a User model with a hasOne relationship to a Profile model.

First, your database tables need to be keyed correctly. For a hasOne relationship to work, one table has to contain a foreign key that points to a record in the other. In this case the profiles table will contain a field called user_id. The basic pattern is:

hasOne: the other model contains the foreign key.
Relation Schema
Apple hasOne Banana bananas.apple_id
User hasOne Profile profiles.user_id
Doctor hasOne Mentor mentors.doctor_id

The User model file will be saved in /app/models/user.php. To define the ‘User hasOne Profile’ association, add the $hasOne property to the model class. Remember to have a Profile model in /app/models/profile.php, or the association won’t work.

<?php

class User extends AppModel {
    var $name = 'User';                
    var $hasOne = 'Profile';   
}
?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasOne = 'Profile';
  5. }
  6. ?>

There are two ways to describe this relationship in your model files. The simplest method is to set the $hasOne attribute to a string containing the classname of the associated model, as we’ve done above.

If you need more control, you can define your associations using array syntax. For example, you might want to limit the association to include only certain records.

<?php

class User extends AppModel {
    var $name = 'User';          
    var $hasOne = array(
        'Profile' => array(
            'className'    => 'Profile',
            'conditions'   => array('Profile.published' => '1'),
            'dependent'    => true
        )
    );    
}
?>
  1. <?php
  2. class User extends AppModel {
  3. var $name = 'User';
  4. var $hasOne = array(
  5. 'Profile' => array(
  6. 'className' => 'Profile',
  7. 'conditions' => array('Profile.published' => '1'),
  8. 'dependent' => true
  9. )
  10. );
  11. }
  12. ?>

Possible keys for hasOne association arrays include:

  • className: the classname of the model being associated to the current model. If you’re defining a ‘User hasOne Profile’ relationship, the className key should equal ‘Profile.’
  • foreignKey: the name of the foreign key found in the other model. This is especially handy if you need to define multiple hasOne relationships. The default value for this key is the underscored, singular name of the current model, suffixed with ‘_id’. In the example above it would default to 'user_id'.
  • conditions: An SQL fragment used to filter related model records. It’s good practice to use model names in SQL fragments: “Profile.approved = 1” is always better than just “approved = 1.”
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • dependent: When the dependent key is set to true, and the model’s delete() method is called with the cascade parameter set to true, associated model records are also deleted. In this case we set it true so that deleting a User will also delete her associated Profile.

Once this association has been defined, find operations on the User model will also fetch a related Profile record if it exists:

//Sample results from a $this->User->find() call.

Array
(
    [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    [Profile] => Array
        (
            [id] => 12
            [user_id] => 121
            [skill] => Baking Cakes
            [created] => 2007-05-01 10:31:01
        )
)

Diferencias

Lines: 1-103Lines: 1-83
 <title>hasOne</title> <title>hasOne</title>
-<p>r /> Let’s set up a User model with a hasOne relationship to a Profile model. /></p>
<p>r /> First, your database tables need to be keyed correctly. For a hasOne relationship to work, one table has to contain a foreign key that points to a record in the other. In this case the profiles table will contain a field called user_id. The basic pattern is:
</p>
+<p>Configuremos un modelo Usuario con una relación &lt;em>hasOne&lt;/em> con un modelo Perfil.</p>

<p>Primero, necesitas establecer las claves de tus tablas de base de datos correctamente. Para que funcione una relación &lt;em>hasOne</em> correctamente, una tabla ha de contener una clave foránea que apunte a un registro en la otra. En este caso, la tabla 'perfiles' contendrá un campo llamado <code>usuario_id</code>. El patrón básico es:</p>
 <table> <table>
- <caption><strong>hasOne:</strong> the <em>other</em> model contains the foreign key.</caption> + <caption><strong>hasOne:</strong> el <em>otro</em> modelo contiene la clave foránea.</caption>
  <tr>  <tr>
- <th>Relation</th>
<th>Schema</th>
+ <th>Relación</th>
<th>Esquema</th>
  </tr>  </tr>
  <tr>  <tr>
- <td>Apple hasOne Banana</td>
<td>bananas.apple_id</td>
+ <td>Manzana hasOne Plátano</td>
<td>plananos.manzana_id</td>
  </tr>  </tr>
  <tr>  <tr>
- <td>User hasOne Profile</td>
<td>profiles.user_id</td>
+ <td>Usuario hasOne Perfil</td>
<td>perfiles.usuario_id</td>
  </tr>  </tr>
  <tr>  <tr>
  <td>Doctor hasOne Mentor</td>  <td>Doctor hasOne Mentor</td>
- <td>mentors.doctor_id</td> + <td>mentores.doctor_id</td>
  </tr>  </tr>
 </table> </table>
-<p> /> The User model file will be saved in /app/models/user.php. To define the User hasOne Profile association, add the $hasOne property to the model class. Remember to have a Profile model in /app/models/profile.php, or the association won’t work.
</p>
+
<p>El archivo del modelo Usuario se grabado en <kbd>/app/models/usuario.php</kbd>. Para definir la asociación 'Usuario <em>hasOne</em> Perfil', añade la propiedad &lt;code>$hasOne</code&gt; a la clase del modelo. Recuerda tener un modelo Perfil en <kbd>/app/models/perfil.php</kbd>, o la asociación no funcionará.</p>
 <pre> <pre>
 &lt;?php &lt;?php
-
class User extends AppModel {
var $name = 'User';
var $hasOne = 'Profile';
+class Usuario extends AppModel {
var $name = 'Usuario';
var $hasOne = 'Perfil';
 } }
 ?&gt; ?&gt;
 </pre> </pre>
-<p>
There
are two ways to describe this relationship in your model files. The simplest method is to set the $hasOne attribute to a string containing the classname of the associated model, as we’ve done above.
</p>
<p>
If you
need more control, you can define your associations using array syntax. For example, you might want to limit the association to include only certain records.
</p>
+
<p>Hay dos manera de describir esta relación en tus archivos del modelo. La manera más simple es establecer el atributo &lt;code>$hasOne&lt;/code&gt; a una cadena de caracteres conteniendo el nombre de la clase del modelo asociado, como hemos hecho arriba.</p>

<p>Si necesitas más control, puedes definir tus asociaciones utilizando sintaxis de arrays. Por ejemplo, podrías desear limitar la asociación para incluir sólo ciertos registros.</p>
 <pre> <pre>
 &lt;?php &lt;?php
-
class User extends AppModel {
var $name = 'User';
+class Usuario extends AppModel {
var $name = 'Usuario';
  var $hasOne = array(  var $hasOne = array(
- 'Profile' =&gt; array(
'className' =&gt; 'Profile',
'conditions' =&gt; array('Profile.published' =&gt; '1'),
+ 'Perfil' =&gt; array(
'className' =&gt; 'Perfil',
'conditions' =&gt; array('Perfil.publicado' =&gt; '1'),
  'dependent' =&gt; true  'dependent' =&gt; true
  )  )
  );   );
 } }
 ?&gt; ?&gt;
 </pre> </pre>
-<p> /> Possible keys for hasOne association arrays include:
</p>
+
<p>Las claves posibles para los arrays de asociaciones <em>hasOne</em> incluyen:</p>
 <ul> <ul>
- <li>
<strong>className</strong>: the classname of the model being associated to the current model. If you’re defining a User hasOne Profile’ relationship, the className key should equal Profile.
</li>
<li>
<strong>foreignKey</strong>: the name of the foreign key found in the other model. This is especially handy if you need to define multiple hasOne relationships. The default value for this key is the underscored, singular name of the current model, suffixed with _id. In the example above it would default to 'user_id'.
</li>
<li>
<strong>conditions</strong>: An SQL fragment used to filter related model records. It’s good practice to use model names in SQL fragments: Profile.approved = 1 is always better than just approved = 1.
</li>
<li>
<strong>fields</strong>: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
</li>
<li>
<strong>dependent</strong>: When the dependent key is set to true, and the model’s delete() method is called with the cascade parameter set to true, associated model records are also deleted. In this case we set it true so that deleting a User will also delete her associated Profile.
</li>
+ <li><strong>className</strong>: el nombre de la clase del modelo que está siendo asociado al modelo actual. si estás definiendo una relación 'Usuario <em>hasOne</em> Perfil', la clave <code>className</code> debería ser igual a 'Perfil'.</li>
<li><strong>foreignKey</strong>: el nombre de la clave foránea que se encuentra en el otro modelo. Esto es especialmente útil si necesitas definir múltiples relaciones <em>hasOne&lt;/em>. El valor por defecto para esta clave es el nombre en singular del modelo actual, seguido del sufijo '_id'. En el ejemplo de arriba, debería ser por defecto 'usuario_id'.</li>
<li><strong>conditions</strong>: Un fragmento SQL usado para filtrar registros del modelo relacionado. Es buena práctica usar nombres de modelos en los fragmentos SQL: 'Perfil.aprobado = 1' siempre es mejor que simplemente 'aprobado = 1'.</li>
<li><strong>fields</strong>: Una lista de campos a ser devueltos cuando se traen los datos del modelo asociado. Por defecto devuelve todos los campos.</li>
<li><strong>dependent</strong>: Cuando la clave <code>dependent</code> se establece a &lt;code>true</code>, y el método <code>delete()</code&gt; del modelo es llamado con el parámetro &lt;code>$cascada&lt;/code&gt; con valor <code>true</code>, los registros del modelo asociado también son borrados. En este caso lo ponemos a <code>true</code&gt; de manera que borrando un Usuario también borrasu Perfil asociado.</li>
 </ul> </ul>
-<p> 
- Once this association has been defined, find operations on the User model will also fetch a related Profile record if it exists: 
-</p> 
-<pre class="plain"> 
-//Sample results from a $this-&gt;User-&gt;find() call. 
 +<p>Una vez que esta asociación ha sido definida, las operaciones de búsqueda en el modelo usuario traerán también el registro Perfil relacionado si existe:</p>
 +<pre class="plain">
 +// Resultados de ejemplo de una llamada a $this-&gt;Usuario-&gt;find()
 Array Array
 ( (
- [User] =&gt; Array + [Usuario] =&gt; Array
  (  (
  [id] =&gt; 121  [id] =&gt; 121
  [name] =&gt; Gwoo the Kungwoo  [name] =&gt; Gwoo the Kungwoo
  [created] =&gt; 2007-05-01 10:31:01  [created] =&gt; 2007-05-01 10:31:01
  )  )
- [Profile] =&gt; Array + [Perfil] =&gt; Array
  (  (
  [id] =&gt; 12  [id] =&gt; 12
  [user_id] =&gt; 121  [user_id] =&gt; 121
- [skill] =&gt; Baking Cakes + [habilidad] =&gt; Hornear Pasteles
  [created] =&gt; 2007-05-01 10:31:01  [created] =&gt; 2007-05-01 10:31:01
  )  )
 ) )
 </pre> </pre>