湯呑み茶碗の開発日記

WEBシステム屋の私がUnityの趣味開発で得た技術等をブログに載せていきます。

UnityでSqliteを自動化 ~データ取得条件指定編~

データ取得編の記事の続きです。

UnityでSqliteを自動化 ~データ取得編~ - 湯呑み茶碗の開発日記

この記事ではデータを取得する方法について紹介しました。
今回はデータを取得する際に条件を指定したり、テーブルを結合していきたいと思います。


前回と同じく「SqliteTableService.cs」を見ていきます。


取得条件指定

データを取得する際に条件を指定している関数部分に着目していきます。


/// <summary>
/// Get to sort the master data
/// マスターデータをソートして取得
/// </summary>
/// <param name="masterCategory"></param>
/// <returns></returns>
public static List<MasterData> GetMasterDataList(string masterCategory)
{
    DataAccess dataAccess = DataAccess.Instance;
    // Init
    dataAccess.Init(typeof(MasterData));
    dataAccess.AddCondition("MasterCategory", masterCategory, typeof(MasterData), true);
    
    // Set the sort item
    // ソート項目を設定
    dataAccess.AddOrderByColumns("Seq", typeof(MasterData), true);
    dataAccess.AddOrderByColumns("MasterCategory", typeof(MasterData), false);

    return dataAccess.GetDataList<MasterData>();
}

この関数では条件指定とソート指定を行っています。そして実行されたSqlite文がこちら。

f:id:yunomichawan:20160920010601p:plain

昇順のソートと、確認のため降順ソートをしてデータを取得するとこんな感じです。

シーケンス(Seq)のソート方向でデータの取得順が変わっていることが分かります。

昇順

f:id:yunomichawan:20160920010317p:plain

降順

f:id:yunomichawan:20160920011008p:plain


テーブル結合

次はテーブルを結合してデータを取得している関数に着目していきます。
ここからはSqliteの構文に関する知識が若干必要になってきます。


/// <summary>
/// Get the character data that brute string to PartyId
/// パーティーテーブルに紐づくキャラクターデータを取得
/// </summary>
/// <param name="partyId"></param>
/// <returns></returns>
public static List<CharacterData> GetPartyCharacterList(string partyId)
{
    DataAccess dataAccess = DataAccess.Instance;
    // 最初にセレクトしたいテーブルで初期化
    dataAccess.Init(typeof(PartyTable));
    
    // It performs an internal table joins in PartyId
    // PartyIdでテーブルの内部結合を行う
    dataAccess.AddJoinTable(typeof(PartyTable), typeof(PartyCharacterTable), "PartyId");
    
    // It performs an internal table joins in CharacterId
    // CharacterIdでテーブルの内部結合を行う
    dataAccess.AddJoinTable(typeof(PartyCharacterTable), typeof(CharacterData), "CharacterId", "CharacterId");
    
    // Set condition
    // 条件を指定する
    dataAccess.AddCondition("PartyId", partyId, typeof(PartyTable), true);
    
    // Get the bound table
    // 結合したテーブルを取得
    DataTable dataTable = dataAccess.GetDataTable();

    // Get the PartyTable from the combined table
    // 結合されたテーブルからPartyTableを取得
    List<PartyTable> partyTableList = DataBinding<PartyTable>.DataTableToObjectList(dataTable);

    // Get the PartyTable from the combined table
    // 結合されたテーブルからCharacterDataを取得
    List<CharacterData> characterDataList = DataBinding<CharacterData>.DataTableToObjectList(dataTable);

    return characterDataList;
}

この関数では2つのテーブルと結合し合計3つのテーブルからデータを取得しています。そして実行されたSqlite文がこちら。

f:id:yunomichawan:20160920010659p:plain

 

取得されたデータがこちらになります。デバッグで確認するとデータが取れていることが確認できます。

f:id:yunomichawan:20160920010219p:plain

パーティーに設定されているキャラクターリストを取得することを想定しています。

ソーシャルゲームによくあるパーティー構成を想像して頂くとわかりやすいかもしれません。

 

もうちょっと続きます。