首页 > 解决方案 > 检查两个集合的差异

问题描述

我有 2 个变量:一个存储表的内容,一个存储检查数据库中所有键的 sql 脚本。

$indexes = DB::connection('sqlsrv2')->table('indexes')->get();

$dbIndexes = DB::connection('sqlsrv')->select
        ("
                select 
                    schema_name(t.[schema_id]) + '.' + t.[name] as table_view,
                    substring(column_names, 1, len(column_names)-1) as [columns],
                    case when i.is_primary_key = 1 then 'Primary_key'
                    when i.is_unique = 1 then 'Unique'
                    else 'Not_unique' end as [type],
                    i.[name] as index_name,
                    i.index_id
                    from sys.objects t
                    inner join sys.indexes i
                    on t.[object_id] = i.[object_id]
                    cross apply 
                    (
                            select col.[name] + ', '
                            from sys.index_columns ic
                        inner join sys.columns col on ic.[object_id] = col.[object_id] and ic.column_id = col.column_id
                        where ic.[object_id] = t.[object_id]
                        and ic.index_id = i.index_id
                        order by col.column_id
                        for xml path ('')
                    ) D (column_names)
                    where t.is_ms_shipped <> 1
                    and index_id > 0
        ");

我需要查看表中的内容是否也在 sql 脚本中,如果不删除该行。我已经尝试过“diff”和“diffAssoc”方法,但显示所有记录都是不同的。

$diff = $indexes->diffAssoc(get_object_vars(collect($dbIndexes)));

标签: phplaravel

解决方案


我所做的是,而不是:

$indexes = DB::connection('sqlsrv2')->table('indexes')->get();

谁返回对象集合,我使用过:

$indexes = DB::connection('sqlsrv2')->select("select * from indexes");

谁返回一个数组。而两者的对比是这样的:

$indexes = array_map('serialize', $indexes);

$dbIndexes = array_map('serialize', $dbIndexes);

$diff = array_merge(array_diff($indexes,$dbIndexes),array_diff($dbIndexes,$indexes));

通过这种方式,它检查两种方式的差异。如果您仅以一种方式进行检查,它将显示差异。


推荐阅读