Falcon: how to get great models?

Using the Phalcon model , how can I get individual rows when retrieving rows using the find() method.

+5
source share
6 answers

Using the builder:

The main implementation for the following example:

  $queryBuilder = $this->getDI()->getModelsManager() ->createBuilder() ->addFrom('tableName', 't'); 

Distinctive team:

  $queryBuilder->distinct('t.id'); 

The column also works, but is not recommended:

  $queryBuilder->columns('DISTINCT(t.id) AS id') 

Using strictly models:

  // we are waiting for it, but may still not be implemented TableModel::find(array('distinct' => 'id')) 

To count:

  TableModel::count(array("distinct" => "id")); 

And a less recommended method according to the previous answer:

  TableModel::find(array('columns' => 'distinct(id)')) 

And a link to imo best docs .

In addition, there are some problems in Phalcon 2.0.2 .

+8
source

If you have specified some columns, you can use:

  $result = Word::find(['columns'=>'distinct foo']); 
+3
source

In some cases, you can use it when initializing the model, here is an example:

 /** * Class MyModel * @property \Phalcon\Mvc\Model\Resultset\Simple referenceAlias * @method int countReferenceAlias */ class MyModel extends \Phalcon\Mvc\Model { public function initialize(): void { $this->setSource('my_model'); $this->hasMany('id', 'ReferenceModel', 'reference_id', [ 'alias' => 'referenceAlias', 'params' => ['distinct' => 'user_id'] ]); } } 

Therefore, later you can make calls this way:

 print $myModel->countReferenceAlias(); 

or

 foreach($myModel->referenceAlias() as $userReference){ print $userReference->user->getName(); } 
0
source

You can define this in the model :: initialize () method:

 $this->hasManyToMany( 'asset_id', 'NameSpace\AssetsCategory', 'asset_id', 'category_id', 'NameSpace\Category', 'category_id', [ 'alias' => 'SimilarAssets', 'params' => [ 'group' => 'NameSpace\Category.category_id' // remove duplicate data ] ] ); 
0
source

Use the group keyword.

 $result = TableModel::find(array("x_id = $x_id","group"=>"uid")); 

You can add as many extra arguments to the first section with x_id as

 x_id = $x_id AND y_id = 100 

The second part is to specify the field that you want to group for the TableModel.

-1
source

In phalcon 3.x, it looks like it is different from Model Manager, and a separate method takes a boolean value as a parameter. Therefore, to make a separate column, you must do this:

  $queryBuilder = $this->getDI()->getModelsManager() ->createBuilder() ->addFrom('tableName', 't') ->columns('t.myColumn') ->distinct(true) ->getQuery() ->execute(); 
-1
source

All Articles