Datasets - HL Vanilla Community
<main> <article class="userContent"> <div class="embedExternal embedImage display-large float-none"> <div class="embedExternal-content"> <a class="embedImage-link" href="https://us.v-cdn.net/6030677/uploads/P3P498008LIT/microsoftteams-image-288-29.png" rel="nofollow noreferrer noopener ugc" target="_blank"> <img class="embedImage-img" src="https://us.v-cdn.net/6030677/uploads/P3P498008LIT/microsoftteams-image-288-29.png" alt="MicrosoftTeams-image (8).png" height="108" width="1356" loading="lazy" data-display-size="large" data-float="none"></img></a> </div> </div> <p>The <code class="code codeInline" spellcheck="false" tabindex="0">Gdn_Dataset</code> object is a way to store data. Most of the time, this data is the result of a query to the database. When you use our <a href="https://docs.vanillaforums.com/developer/framework/database" rel="nofollow noreferrer ugc">database object</a> (as you always should) to execute a database select query, it will return a dataset.</p><p>Here are a few commonly used methods you’ll want to know about:</p><ul><li><code class="code codeInline" spellcheck="false" tabindex="0">count()</code> returns the number of records in the dataset.</li><li><code class="code codeInline" spellcheck="false" tabindex="0">firstRow()</code> returns the first record in the dataset.</li><li><code class="code codeInline" spellcheck="false" tabindex="0">resultArray()</code> returns an array of all the data in the dataset (often used directly in a <code class="code codeInline" spellcheck="false" tabindex="0">foreach</code> loop).</li></ul><p>Just as the database object is chainable, so is the dataset object. The database’s <code class="code codeInline" spellcheck="false" tabindex="0">get()</code> method returns the resulting dataset object, so the two chain together seamlessly.</p><p>This example gets the number of records in the database matching a query:</p><pre class="code codeBlock" spellcheck="false" tabindex="0">$howMany = Gdn::sql() ->select('*') ->from('GDN_SomeTable') ->get() // Now it's a dataset! ->count(); </pre><p>This example is a common construct for iterating through records returned from a database:</p><pre class="code codeBlock" spellcheck="false" tabindex="0">$users = Gdn::sql() ->select('Name') ->from('User') ->where('CountComments', 1) ->get(); foreach ($users->resultArray() as $user) { // Do something to each user with 1 comment. } </pre><p>Another use case for datasets is joining datasets together after separate database queries, which can result in better performance. This is simply done by adding data to the array or object dataset manually. See the <code class="code codeInline" spellcheck="false" tabindex="0">joinUsers()</code> method in the <code class="code codeInline" spellcheck="false" tabindex="0">UserModel</code> for one such example.</p> </article> </main>