Reputation: 13240
How can I instantiate a model and get all columns already declared in the instance?
$modelA = User::findFirst();
echo $modelA->id; //OK
$modelB = new User();
echo $modelA->id; //Id is undeclared causing errors instead of returning blank
Currently I need to declare by hand the model columns in the event onConstruct
but I want to make use of the database introspection strategy and get properties declared from the table schema schema when I use new User();
.
Anyone knows something that can help me out?!
Upvotes: 0
Views: 769
Reputation: 626
Try the Annotations Strategy mentioned on that page.
So, something like
class Test extends \Phalcon\Mvc\Model
{
/**
* @Primary
* @Identity
* @Column(type="integer", nullable=false)
*/
public $id;
...
Get an instance of the meta-data adapter from the services container:
<?php
use Phalcon\Mvc\Model\MetaData\Apc as ApcMetaData,
Phalcon\Mvc\Model\MetaData\Strategy\Annotations as StrategyAnnotations;
$di['modelsMetadata'] = function() {
// Instantiate a meta-data adapter
$metaData = new ApcMetaData(array(
"lifetime" => 86400,
"prefix" => "my-prefix"
));
Get the columns for your model like so:
<?php
$test = new Test();
// Get Phalcon\Mvc\Model\Metadata instance
$metaData = $test->getModelsMetaData();
// Get fields names
$attributes = $metaData->getAttributes($test);
print_r($attributes);
// Get fields data types
$dataTypes = $metaData->getDataTypes($test);
print_r($dataTypes);
All of the above can be found in the link.
Also check out the MetaData APIs.
Hope that helps.
Upvotes: 2