We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Models with values already selected

Hello,

I have for example the following model:

<?php
class Articles extends \Phalcon\Mvc\Model
{
    /**
     * @var integer
     */
    public $id;

    /**
     * @var string
     */
    public $languagekey;

    /**
     * @var integer
     *
     */
    public $iconid;

    /**
     * @var integer
     *
     */
    public $publishid;  

    /**
     * @var string
     */
    public $pagetitle;

    /**
     * @var string
     */
    public $listtitle;

    /**
     * @var string
     */
    public $listdescription;

    /**
     * @var string
     */
    public $content;

    /**
     * @var string
     */
    public $seotitle;

    /**
     * @var string
     */
    public $seodescription;

    /**
     * @var string
     */
    public $seokeywords;

    /**
     * @var string
     */
    public $websitetitle;

    /**
     * @var string
     */
    public $websiteurl;

    /**
     * @var string
     */
    public $filename;

    /**
     * @var integer
     */
    public $ordernumber;

    /**
     * @var string
     */
    public $adddate;

    /**
     * @var string
     */
    public $modifydate;

    /**
     * @var string
     */
    public $publishdate;

    /**
     * @var string
     */
    public $expiredate;
}

This model works fine. For my website I use this model in many controllers, and I have to tho something like this several times:

$article=Articles::findFirst(array("id = '12'", "languagekey = 'en'", "publishdate < date('Y-m-d')", "expiredate > date('Y-m-d')"));

My question:

Is there an option to preselect some fields, so I only need to use this

$article=Articles::findFirst(12);`

and that (in this example) the languagekey, publishdate and expiredate are automatically selected with the right conditions.



2.6k

@mywebcontent

Hi! I am doing it this way:

class Articles extends \Phalcon\Mvc\Model {

    //your model definition...

  public static function getMyAwesomeArticles() {

    return self::find(array(
        "id = '12'",
        "languagekey = 'en'",
        "publishdate < date('Y-m-d')",
        "expiredate > date('Y-m-d')"
    ));
  }
}

I think it might be helpful.

Notes:

  1. I am not an expert. May be there is a better solution.
  2. Please note that the method is static and I use keyword self.
  3. What is the sense of adding these preselected fields and asking for an article with specified id? How many articles do you have with id=12?


2.6k

Forgot to add, in your controller you write:


$article = Articles::getMyAwesomeArticles();