2

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Tijmen
  • 149
  • 1
  • 6
  • 1
    The magic you're missing is Ruby. I don't mean to be a troll, it's just that Cake is an attempt to get the magic of Ruby into PHP without realizing that PHP just isn't up to it. – Chuck Vose Feb 18 '10 at 21:47
  • 1
    Why would you assign a value in an array to a single variable? That's pretty inefficient. You don't need to use $field1; just do a Model::find() and use the returned value effectively. – Travis Leleu Feb 19 '10 at 00:36

3 Answers3

4

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

$this->User->find('all', array('fields'=>array('field1', 'field2')));
Aziz
  • 859
  • 6
  • 16
2
$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,190
  • 3
  • 28
  • 37
0

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;");
iwcoder
  • 144
  • 6