//Pascal Script
function GetRidTbName(fName, fRid: string): string;
var
  L1, L2: Integer;
  S: string;
begin
  Result := '';
  if Pos(fRid, fName)=0 then
    Exit;
  L1 := Length(fName);
  L2 := Length(fRid);
  if L1<=L2 then
    Exit;
  S := UpperCase(Copy(fName,L1-L2+1,L2));
  if S=UpperCase(fRid) then
    Result := Copy(fName,1,L1-L2);
end;

function GetTableOfName(AName: string): TCtMetaTable;
var
  I: integer;
  md: TCtDataModelGraph;
  tb: TCtMetaTable;
begin
  Result := nil;
  if Trim(AName) = '' then
    Exit;
  for I := 0 to AllModels.Count - 1 do
  begin
    md := AllModels.Items[I];

    tb := TCtMetaTable(md.Tables.ItemByName(AName, False));
    if tb = nil then
      Continue;
    Result := tb;
    Exit;
  end;
end;

var
  I, J, K, C: Integer;
  md: TCtDataModelGraph;
  tb, rtb: TCtMetaTable;
  fd: TCtMetaField;
  fdRid, fdRtb, rfdn, res: string;
  comp: TComponent;
begin
  fdRid := Prompt('查找当前模型中的外键，请指定外键字段字段名后缀（如：_id）：','');
  if fdRid = '' then
    Exit;
  c:=0;
  res := '';
  for I:=0 to AllModels.Count-1 do
  if AllModels.Items[I] = AllModels.CurDataModel then
  begin
    md := AllModels.Items[I];

    for J:=0 to md.Tables.Count-1 do
    begin
      tb := md.Tables.Items[J];

      for K:=0 to tb.MetaFields.Count -1 do
      begin
        fd := tb.MetaFields.Items[K];
        if (fd.KeyFieldType=cfktId) or (fd.KeyFieldType=cfktRid) then
          Continue;
        if fd.RelateTable <> '' then
          Continue;
        if fd.RelateField <> '' then
          Continue;
        fdRtb := GetRidTbName(fd.Name, fdRid);
        if fdRtb<>'' then
        begin
          rtb := GetTableOfName(fdRtb);
          if rtb <> nil then
          begin
            rfdn := rtb.GetPrimaryKeyNames('');
            if (rfdn<>'') and (Pos(',', rfdn)=0) then
            begin
              fd.KeyFieldType := cfKtRid;
              fd.RelateTable := rtb.Name;
              fd.RelateField := rfdn;
              SyncTableProps(tb);
              res :=res+' '+tb.Name+'.'+fd.Name;
              Inc(C);
            end;
          end;
        end;
      end;
    end;
  end;


  if C>0 then
  begin     
    TAction(FindChildComp(Application.MainForm,'actRefresh')).Execute;
    Alert('已添加'+IntToStr(C)+'个外键字段：'+res);
  end
  else
    Alert('未找到可添加的外键字段');
end.
