Kohana 3.1 ORM - Conditional Parameters
-
25-05-2021 - |
题
I am trying to achieve a very simple goal, however it does not seem to be working. I wish to use Kohana's ORM and conditionally add certain parameters.
For instance:
$query = ORM::factory('user')
->where('foo', '=', 'bar');
if (isset($some_var))
$query->where('field', '=', $some_var);
$query->find_all();
One would think this should work, but all I get from $query
is a big fat nothing. Any suggestions I would greatly appreciate! Thanks.
EDIT:
The simple example on this Kohana page even shows a similar query: http://kohanaframework.org/3.1/guide/orm/examples/simple
...But even when I create a 'user' model instance and then try to find_all()
in a separate statement, I get nothing.
This works:
$query = ORM::factory('user')->find_all();
This doesn't work:
$query = ORM::factory('user');
$query->find_all();
Possible bug??
解决方案
In your example that works, you are assigning the value returned from find_all() to $query. While in the example that is not working, you are not assigning the value returned by find_all() at all.
$query = ORM::factory('user');
$result = $query->find_all();
// you may now loop over $result
When you look over the api, you will see that find() and find_all() work differently.
其他提示
Your code is perfectly fine, as ORM::where
method returns ORM object, so there is no problem with method chaining. You should look for the errors in other place (perhaps your $some_var
is set but may be empty, therefore your condition may look different then expected). I'd try with this small change:
if (!empty($some_var))
$query->where('field', '=', $some_var);