views:

88

answers:

3

I'm new to CakePHP, and still figuring out the basics. Right now I'm a bit mystified by the process to get one or more fields from a model (from inside another linked model).

So far, I have this:

$this->user->id = 123;
$this->User->read();
$field1 = $this->User->data['User']['field1'];
$field2 = $this->User->data['User']['field2'];

Which seems awfully verbose.

And this:

$this->user->id = 123;
$field1 = $this->User->field('field1');
$field1 = $this->User->field('field2');

Which seems less long, but results in two queries.

What I used to do in these situations, pre-Cake:

$this->User = new User(123);
$field1 = $this->User->field1;
$field2 = $this->User->field2;

or when I felt like typing:

this->User = new User(123);
$field1 = $this->User->getFieldOne();
$field2 = $this->User->getFieldTwo();

So, the question: am I missing some magic in CakePHP by which to accomplish this task, or do I have to live with typing a lot?

+2  A: 
$arrayOfFiels = array('field1', 'field2');
$this->User->id = 123;
$userFields = $this->User->read($arrayOfFields);

Or something like:

$userFields = $this->User->read(null, 123);

In both cases, $userFields will be an array with User #123 data. In the second one, due to the first argument set as null, all fields will be fetched. Second argument (optional) sets an id, which can also be pre-set earlier like in the first example.

PawelMysior
+3  A: 

You will never believe, but there is a short way :-)

$this->User->find('all', array('fields'=>array('field1', 'field2')));
Aziz
A: 

you can either use 'read' or 'find' or 'query' to get data from model

read

$fields = array('field1','field2');
$this->data = $this->User->read( $fields,$someid );

find

$this->data = $this->User->find('all',array('fields'=>array('field1','field2') );

query

$this->data = $this->User->query("select field1,field2 from user where id=$someid;");
Ricky