I would like to define the association of the following two tables in cakephp3.
Table 1: Users Table
Table that defines user characteristics.
Table 2: languages table
Master table that defines the programming language.
The users table has columns main_language and sub_language that refer to the id defined in the languages table.
In this case, how should I define the association in cakephp3?I look forward to your kind cooperation.
cakephp
Table class corresponding to the users
table UsersTable
, language
table corresponding Table classLanguagesTable is already defined.
For question table design, the relationship between users
→language
is belongsTo.
belongsTo association|Association - Connecting models to each other - 3.5
Define the relationship in the initialize()
method in UsersTable
as follows:
class UsersTable extensions Table
{
public function initialize (array$config)
{
// ...
$this->belongsTo('MainLanguage', [//Relation name (any name))
'className' = > 'Languages', // Destination table class name
'foreignKey' = > 'main_language', // The name of the foreign key on the table in question
'propertyName' = > 'main_language_obj', // property name to be associated when entityized (any name specified)
]);
$this->belongsTo('SubLanguage',[
'className' = > 'Languages',
'foreignKey' = > 'sub_language',
'propertyName' = > 'sub_language_obj',
]);
}
}
By making the above specification, you can retrieve it as follows:
$user=$this->Users->find('all')
->contain(['MainLanguage', 'SubLanguage') // Remember the contain clause
->first();
// See languages.name in main_language
$user->main_language_obj->name;
// See languages.name in sub_language
$user->sub_language_obj->name;
In addition, main_language
, sub_language
which is an external key to the users table should be main_language_id
, sub_language_id
, sub_language_id
, and used the property name naturally.
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
915 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
618 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.