How do I use the findBy magic find functions WITH $fields optional parameters?
try this:
$result = $this->findById($id, array('Alpha.name'));
where $id
is an id of record you're searching for and Alpha.name
is a field you need (e.g. name
from model Alpha
)
generalopinion
Coding enthusiast, entrepreneur, Systems Administrator, web designer. I enjoy using and working with technology.
Updated on June 27, 2022Comments
-
generalopinion almost 2 years
Was considering utilizing the magic
findBy
functions on a model today and encountered an issue when attempting to set optional parameters for the function. Here is what I tried.$result = $this->findById($id['Alpha.name']);
So to explain, I'm attempting to find a record with a specific
id
and only return the value of thename
field. According to the documentation, there is a way to do this.The findBy magic functions also accept some optional parameters:
findBy<fieldName>(string $value[, mixed $fields[, mixed $order]]);
When I do a simple
findBy($id)
I do get a result set. But with parameters, I get nothing. I know there are other ways to do this but was just curious if anyone has had any success using these magic functions with additional parameters? -
generalopinion almost 13 yearsThis worked. I will give credit for this answer since the problem was with the syntax (i.e. I was using incorrect syntax). However, I discovered that if the model has
hasMany
relationships, those relationships will be returned. This model hadhasOne
relationships but those weren't returned. It didn't have anybelongsTo
relationships so I don't know if those would've been returned or not. -
zergussino almost 13 years@generalopinion try to set
$this->Alpha->recursive = 1
to get model with related models, e.g.Alpha
with corresponding data fromhasOne
modelBeta
-
generalopinion almost 13 yearsSweet. I assume that doing
$this->Alpha->recursive = -1
would return only the model without any relationships?