association of cakephp3

Asked 2 years ago, Updated 2 years ago, 47 views

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

2022-09-30 16:58

1 Answers

Table class corresponding to the users table UsersTable, language table corresponding Table classLanguagesTable is already defined.

For question table design, the relationship between userslanguage 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.


2022-09-30 16:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.