Friday, January 14, 2022

[FIXED] How to get all the tables name of particular type of associations with current table

Issue

I want to get all the table names, associated with my current table. Let's consider my current table is Products, I have association like

$this->belongsToMany('Categories', [
        'className' => 'Categories',
        'foreignKey' => 'product_id',
        'targetForeignKey' => 'category_id',
        'joinTable' => 'categories_products'
    ]);
$this->belongsToMany('Images', [
        'className' => 'Images',
        'foreignKey' => 'product_id',
        'targetForeignKey' => 'image_id',
        'joinTable' => 'images_products'
    ]);

What I want is the associated table name with products with association type of belongsToMany.

What I did yet is the following code but It returns a object of protected data.

$this->Products->associations()->type('belongsToMany')

Solution

you can loop through the associations and get the table name

$associations =  $this->Products->associations()->type('belongsToMany');

$tables = [];

foreach($associations as $association)
{
    $tables[] = $association->getTarget()->getTable();
}

probably there is also a faster way using Collections



Answered By - arilia

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.