繁体   English   中英

递归函数,用于查找MySQL表的所有依赖项

[英]Recursive function to find all the dependencies of a MySQL table

我有一个数据库,其中有几个相关的表。 例如,表User包含系统中的所有用户。 然后我有一个名为User_friend的索引表,其中包含用户和朋友之间的关系。

我有一个函数loadObject($ class,$ id) ,它被称为:

 loadObject('User', 1);

并返回id = 1的User作为数组,格式如下:

array(
    'id' => 1,
    'username' => 'My user',
    // the following array contains all the entries in User_invited
    'friends' => [2, 3, 4, 5],
    // same for comments
    'comments' => [6, 7]
    'type' => 'User'
);

我试图想出一个递归函数来检查id为1的用户,找到所有的朋友(在'friends'数组中)然后遍历每个值,找到那些用户和它的朋友,直到它到达终点链条没有重复任何条目。

这看起来非常简单。 问题是,除了朋友,我们还可以与评论,事件和许多其他表格建立其他关系。

棘手的部分是这个函数不仅应该与'User'类一起使用,还应该与我们定义的任何类一起使用。

我正在做的是使用某种索引数组来定义哪些索引表引用哪些主表。

例如:

$dependencies = [
    'friends' => 'User'
];

这意味着,当我们找到“朋友”键时,我们应该查询“用户”表。

这是我的代码:

<?php
$class = $_GET['class'];
// if we receive a collection of ids, find each individual object
$ids   = explode(",", $_GET['ids']);

// load all main objects first
foreach($ids as $id) {
    $error = isNumeric($id);
    $results[] = loadObject($class,$id);
}

$preload = $results;
$output = [];

$output = checkPreload($preload);
print json_encode($output);

function checkPreload($preload)
{
    $dependencies = [
        'comment' => 'Comment',
        'friend'  => 'User',
        'enemy'   => 'User',
        'google'  => 'GoogleCalendarService',
        'ical'    => 'ICalCalendarService',
        'owner'   => 'User',
        'invited' => 'User'
    ];

    foreach($preload as $key => $object)
    {
        foreach($object as $property => $values)
        {
            // if the property is an array (has dependencies)
            // i.e. event: [1, 2, 3]
            if(is_array($values) && count($values) > 0)
            {
                // and if the dependency exists in our $dependencies array, find
                // the next Object we have to retrieve
                // i.e. event => CatchAppCalendarEvent
                if(array_key_exists($property, $dependencies))
                {
                    $dependentTable = $dependencies[$property];
                    // find all the ids inside that array of dependencies
                    // i.e. event: [1, 2, 3]
                    // and for each ID load th the object:
                    // i.e. CatchAppCalendarEvent.id = 1, CatchAppCalendarEvent.id = 2, CatchAppCalendarEvent.id = 3
                    foreach($values as $id)
                    {
                        $dependantObject = loadObject($dependencies[$property], $id);
                        // if the object doesn't exist in our $preload array, add it and call the
                        // function again
                        if(!objectDoesntExist($preload, $dependantObject)) {
                            $preload[] = $dependantObject;
                            reset($preload);
                            checkPreload($preload);
                        }
                    }
                }
            }
        }
    }
    return $preload;
}

// 'id' and 'type' together are unique for each entry in the database
function objectDoesntExist($preload, $object)
{
    foreach($preload as $element)
    {
        if($element['type'] == $object['type'] && $element['id'] == $object['id']) {
            return true;
        }
    }
    return false;
}

我很确定我接近解决方案,但我无法理解为什么不工作。 即使我使用函数检查对象是否已插入$ preload数组中,似乎卡在无限循环中。 此外,有时不检查下一组元素。 可能是因为我将数据附加到$ preload变量?

任何帮助都非常受欢迎。 我一直在尝试找到解决依赖关系的算法,但没有应用于MySQL数据库。

谢谢

在一些失败的测试之后,我决定不使用递归方法而是使用迭代方法。

我正在做的是从一个元素开始并将其放在“队列”(数组)中,找到该元素的依赖项,将它们附加到“队列”然后退回并重新检查相同的元素以查看如果还有任何依赖项。

检查依赖关系的函数现在有点不同:

/**
 * This is the code function of our DRA. This function contains an array of dependencies where the keys are the 
 * keys of the object i.e. User.id, User.type, etc. and the values are the dependent classes (tables). The idea
 * is to iterate through this array in our queue of objects. If we find a property in one object that that matches
 * the key, we go to the appropriate class/table (value) to find more dependencies (loadObject2 injects the dependency
 * with it's subsequent dependencies)
 * 
 */
function findAllDependenciesFor($element)
{
    $fields = [
        'property' => 'tableName',
        ...
    ];

    $output = [];

    foreach($element as $key => $val) {
        if(array_key_exists($key, $fields)) {
            if(is_array($val)) {
                foreach($val as $id) {
                    $newElement = loadObject($fields[$key], $id);
                    $output[] = $newElement;
                }
            }
            else {
                // there's been a field conversion at some point in the app and some 'location'
                // columns contain text and numbers (i.e. 'unknown'). Let's force all values to be
                // and integer and avoid loading 0 values.
                $val = (int) $val;
                if($val != 0) {
                    $newElement = loadObject($fields[$key], $val);
                    $output[] = $newElement;
                }
            }

        }
    }

    return $output;
}

我也使用与以前相同的功能来检查“队列”是否已包含该元素(我已将该函数重命名为“objectExists”而不是“objectDoesntExist”。如您所见,我检查类型(表)和id,因为这两个属性的组合对于整个系统/数据库是唯一的。

function objectExists($object, $queue)
{
    foreach($queue as $element) {
        if($object['type'] == $element['type'] && $object['id'] == $element['id']) {
            return true;
        }
    }
    return false;
}

最后,主要功能:

// load all main objects first
foreach($ids as $id) {
    $error = isNumeric($id);
    $results[] = loadObject($class,$id);
}

$queue = $results;
for($i = 0; $i < count($queue); $i++)
{
    // find all dependencies of element
    $newElements = findAllDependenciesFor($queue[$i]);
    foreach($newElements as $object) {
        if(!objectExists($object, $queue)) {
            $queue[] = $object;

            // instead of skipping to the next object in queue, we have to re-check
            // the same object again because is possible that it included new dependencies
            // so let's step back on to re-check the object
            $i--;
        }
    }
    $i++;
}

正如你所看到的,我正在使用常规的“for”而不是“foreach”。 这是因为我需要能够在我的“队列”中前进/后退。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM