Models
While Saturn provides models by default, it is possible to create custom models for database entities. To do so, create a file with the same name as the entity in the models folder alongside the relevant schema.xml file. In this file, write a class with the same name (capitalised) which inherits from either Core\Models\Model or Core\Models\SaticModel, depending on the type of entity.
application/blog/models/blogitem.php
<?php
namespace Application\Blog\Models;
class Blogitem extends \Core\Models\Model
{
public function getCommentCount(): int
{
return $this->comment->count();
}
}
Scopes
Scopes allow you to provide commonly used query conditions. To create a new scope, create a file with the same name as the entity in the scopes folder alongside the relevant schema.xml file. In this file, write a class with the same name (capitalised) which inherits from Core\Models\Scope.
application/blog/models/comment.php
<?php
namespace Application\Blog\Scopes;
class Comment extends \Core\Models\Scope
{
public function visible()
{
return $this->where('is_visible = 1');
}
public function fromAuthor($author)
{
return $this->where('author = %d', $author);
}
}
You can then use this scope when querying the database.
application/blog/blog.php
public function comments()
{
$comments = getAll('comment')->visible()->limit(10);
}