I want to fetch some rows from my databases using the default ORM that Kohana 3 has, but I'm not getting what I want :-)
In my Controller:
$comptes = ORM::factory('compte');
#$comptes->where('empresa_id', '=', 2)->find_all();
$comptes->find_all();
This Query returns 169411 rows in my SQL, but here returns nothing. Of course I can limit using where, limit, or whatever, but I'm experimenting the basics with Kohana.
This returns 1
$result = count($comptes);
In my model view:
<?php var_dump($comptes)?>
produces this:
object(Model_Compte)#16 (34) { ["_has_one":protected]=> array(0) { } ["_belongs_to":protected]=> array(0) { } ["_has_many":protected]=> array(0) { } ["_load_with":protected]=> array(0) { } ["_validation":protected]=> NULL ["_object":protected]=> array(14) { ["id"]=> NULL ["empresa_id"]=> NULL ["codi_compte"]=> NULL ["compte"]=> NULL ["tipus"]=> NULL ["saldo_deure"]=> NULL ["saldo_haver"]=> NULL ["saldo"]=> NULL ["nivell"]=> NULL ["ultim_moviment"]=> NULL ["client_id"]=> NULL...
So this is the model, but how I can get the fetched data?
Also in my view:
foreach ($comptes as $row)
{
echo "<p>$row->codi_compte</p>";
}
?>
But I don't get nothing ...
thanks!
EDIT
This doesn't work:
$comptes = ORM::factory('compte');
$comptes->find_all();
But this works
$comptes = ORM::factory('compte')->find_all();
Why?
And this doesn't work:
$comptes = ORM::factory('compte');
$comptes->where('empresa_id', '=', 2)->find_all();
But again, this works:
$comptes = ORM::factory('compte')->where('empresa_id', '=', 2)->find_all();
This multi-lines examples are from Kohana Web
The correct syntax to get all the rows would be:
$comptes = ORM::factory('compte')->find_all();
Then to check if something has been loaded use $comptes->loaded() (not count($comptes)).
Edit:
To get rows using a where statement, you would write:
$rows = ORM::factory('compte')->where('empresa_id', '=', 2)->find_all();
$comptes = ORM::factory('compte');
$comptes->find_all();
This doesnt work because you didn't assign find_all() result in a variables.
You should write :
$comptes = ORM::factory('compte');
$rows = $comptes->find_all();
If you just want to break it down into multiple lines for readability's sake, this is the simplest method IMO...
Example:
$comptes = ORM::factory('compte')
->where('empresa_id', '=', 2)
->find_all();
$comptes = ORM::factory('compte');
$comptes->find_all();
This doesn't work because you use semicolon.
semicolon means end of statement.
It will work fine if you erase semicolon like this:
$comptes = ORM::factory('compte')
->find_all();
Or make it as 1 line only:
$comptes = ORM::factory('compte')->find_all();
Related
I'm very new on Alfresco.
In a web script i have implemented category search.
var result = search.query("TYPE:\"cm:category\" AND #cm\\:name:CAt*").
but unfortnatly this search on category seems to be case sensitive. the results of search.query("TYPE:\"cm:category\" AND #cm\\:name:CAt*") and search.query("TYPE:\"cm:category\" AND #cm\\:name:cat*") are different.
How can i make search case insensitive?
I guess you should have done something with your lucene or solr configuration.As it seems work perfectly in my instance.Below is working image in my instance.
Or may be you are doing something wrong while testing.As you are executing this in your code may be some problem might be there.
Check your result in node browser.
bellow my webscript (well formatted version)
listData.get.js :
var term = args["term"];
var typeData = args["typeData"];
var searchResult ;
if( "1" == typeData )
{
searchResult = search.query({query: "TYPE:\"sc:site\"" });
}
else if( "2" == typeData )
{
searchResult = search.query({query: "TYPE:\"sc:fonction\"" });
}
else
{
var query = "TYPE:\"cm:category\" AND #cm\\:name:\""+term +"*\"" ;
searchResult = search.query({query: query });
}
And here is the descriptor file
listData.get.desc.xml :
<webscript>
<shortname>Une description du webscript</shortname>
<description> </description>
<url>/listData</url>
<authentication>user</authentication>
</webscript>
So i call webscript with http://localhost:9090/share/proxy/alfresco/listData?term=D
When I query my database with a function passed in the "$where" clause in nodejs, it always return me all documents in the db.
For example, if I do
var stream = timetables.find({$where: function() { return false; }}).stream();
it return me all the documents.
Instead, if I do
var stream = timetables.find({$where: 'function() { return false; }'}).stream();
the function is really executed, and this code doesn't return any document.
The problem is that if I convert in string my function the context's bindinds are removed, and I need them for more complex query. For example:
var n = 1;
var f = function() { return this.number == n; }
var stream = timetables.find({$where: f.toString()}).stream();
// error: n is not defined
Is this a normal behaviour? How can I solve my problem?
Please excuse me for my poor english!
First off, keep in mind that the $where operator should almost never be used for the reasons explained here (credit goes to #WiredPrairie).
Back to your issue, the approach you'd like to take won't work even in the mongodb shell (which explicitly allows naked js functions with the $where operator). The javascript code provided to the $where operator is executed on the mongo server and won't have access to the enclosing environment (the "context bindings").
> db.test.insert({a: 42})
> db.test.find({a: 42})
{ "_id" : ObjectId("5150433c73f604984a7dff91"), "a" : 42 }
> db.test.find({$where: function() { return this.a == 42 }}) // works
{ "_id" : ObjectId("5150433c73f604984a7dff91"), "a" : 42 }
> var local_var = 42
> db.test.find({$where: function() { return this.a == local_var }})
error: {
"$err" : "error on invocation of $where function:\nJS Error: ReferenceError: local_var is not defined nofile_b:1",
"code" : 10071
}
Moreover it looks like that the node.js native mongo driver behaves differently from the shell in that it doesn't automatically serialize a js function you provide in the query object and instead it likely drops the clause altogether. This will leave you with the equivalent of timetables.find({}) which will return all the documents in the collection.
This one is works for me , Just try to store a query as a string in one variable then concat your variable in query string,
var local_var = 42
var query = "{$where: function() { return this.a == "+local_var+"}}"
db.test.find(query)
Store your query into a varibale and use that variable at your find query. It works..... :D
The context will always be that of the mongo database, since the function is executed there. There is no way to share the context between the two instances. You have to rethink the way you query and come up with a different strategy.
You can use a wrapper to pass basic JSON objects, ie. (pardon coffee-script):
# That's the main wrapper.
wrap = (f, args...) ->
"function() { return (#{f}).apply(this, #{JSON.stringify(args)}) }"
# Example 1
where1 = (flag) ->
#myattr == 'foo' or flag
# Example 2 with different arguments
where2 = (foo, options = {}) ->
if foo == options.bar or #_id % 2 == 0
true
else
false
db.collection('coll1').count $where: wrap(where1, true), (err, count) ->
console.log err, count
db.collection('coll1').count $where: wrap(where2, true, bar: true), (err, count) ->
console.log err, count
Your functions are going to be passed as something like:
function () {
return (function (flag) {
return this.myattr === 'foo' || flag;
}).apply(this, [true])
}
...and example 2:
function () {
return (
function (foo, options) {
if (options == null) {
options = {};
}
if (foo === options.bar || this._id % 2 === 0) {
return true;
} else {
return false;
}
}
).apply(this, [ true, { "bar": true } ])
}
This is how it is supposed to be. The drivers don't translate the client code into the mongo function javascript code.
I'm assuming you are using Mongoose to query your database.
If you take a look at the actual Query object implementation, you'll find that only strings are valid arguments for the where prototype.
When using the where clause, you should use it along with the standard operators such as gt, lt that operates on in the path created by the where function.
Remember that Mongoose querying, as in Mongo, is by example, you may want to reconsider your query specification in a more descriptive fashion.
Given a collection of items { url: 'http://blah' }. How can I tell if a record exists where the url is "http://stackoverflow.com"?
P.s. I am communicating with the c# driver
For any of the previous suggestions to be efficient you should be sure that there is an index on the url element. Otherwise a full collection scan will be required.
If you only expect the answer to be 0 or 1, count is probably the most efficient approach. If you think the count will be very large and all you really care about is whether there is one or more, FindOne is the most efficient approach.
It probably doesn't matter that FindOne returns the whole document unless the document is actually rather large. In that case you could tell the server to only return one field (the _id seems the most likely candidate):
var query = Query.EQ("url", "http://stackoverflow.com");
var fields = Fields.Include("_id");
var res = collection.Find(query).SetFields(fields).SetLimit(1).FirstOrDefault();
if (res == null) {
// no match found
}
you simply need check count of items returned by the query:
int count = collection.FindAs<Item>(Query.EQ("url", "http://stackoverflow.com")).Count();
if(count > 0)
{
//do some stuff
}
IMongoQuery query = Query.EQ("url", "http://stackoverflow.com");
var res = collection.FindOne(query);
if(res == null)//don't exist
{
}
Existence of Key in MongoDB can check by using Exists and second parameter as true or false
var filter = builder.Exists("style", false);
var RetrievedData = collection.Find(filter).ToList()
Refference Link
i have a problem with the kohana pagination. i have made a method for paginating elements from the database, (let's say 3 on a page), but, (though the pagination links are there), the pagination is not actually done, meaning i always get listed all the elements of the query.
the code i am using:
in a helper:
public function come_paginate_users(){
$count = Model::factory('user')->count_all(); //echo $count; exit();
$pagination = Pagination::factory(array(
'total_items' => $count,
'items_per_page' => 2,
'auto_hide' => TRUE,
));
$results = Model::factory('user')->order_by('user_id','ASC')->limit($pagination- >items_per_page)->offset($pagination->offset)->find_all();//->execute();
$page_links = $pagination->render();
return $pagination;
}
in the controller:
$pagination = #helper_utilities::come_paginate_users();
$this->view->pagination = $pagination;
and in the view:
<? echo 'Classic style: '.$pagination;?>
but... the pagination is not working. any idea why? thank you!
Actually, You need to return $page_links (wich is rendered html) and $result instead of $pagination object in your come_paginate_users() method
Maybe total_items < items_per_page and auto_hide hides the pagination? Try to set auto_hide to FALSE
My bootstrap.php file looks like this, and all code is embed in welcome controller->action_index.
Kohana::init(array(
'base_url' => '/kohana/',
'index' => 'index.php'
));
Okay if I put the following in in action_index
form::open('test');
the action is /kohana/index.php/test.
So links appear to be absolute to your root install location, accept when I embed links in action_index index.php!!!
html::anchor('controller');
the href is /kohana/controller not /kohana/index.php/controller.
Now if I put
url::site('controller');
the returned value is /kohana/index.php/controller.
So I figured I would just use
html::anchor(url::site('controller'));
But href is now equal to http://localhost/kohana/kohana/index.php/controller.
What in the world is going on, and how do I fix it?
Kohana url system seems well unintuitive and wrong.
Seems like it is some kind of bug in HTML::anchor implementation.
This happens because of 127th line of html.php (v3.1.2)
$uri = URL::site($uri, $protocol, $index);
In this line $index value is FALSE according to the default anchor function value:
public static function anchor($uri, $title = NULL, array $attributes = NULL, $protocol = NULL, $index = FALSE)
So all you can do now is - to pass manually 5th argument as true like:
html::anchor('controller', null, null, null, true);
or extend Kohana_HTML with custom class like:
class HTML extends Kohana_HTML
{
public static function anchor($uri, $title = NULL, array $attributes = NULL, $protocol = NULL, $index = TRUE)
{
return parent::anchor($uri, $title, $attributes, $protocol, $index);
}
}
or to fill a bug on kohana bugtracker so ko devteam decide what to do.