Cakephp 3.x Table Beforefind, unable to stop event - events

Per the documentation on the website of CakePHP: (https://book.cakephp.org/3/en/orm/table-objects.html#beforefind) stopping the event or supplying a return value should stop the find operation.
I'm using the following code in the Beforefind:
$event->stopPropagation();
return false;
But this doesn't seem to have any effect.

The docs need some fixing there, as there's various things wrong with it, returning data won't make any difference, as the return value is never used, also you can't really use the beforeFind event for configuring caching, it's limited to the point of it not being useful, as the event is only being triggered for non-cached queries, and for those it's triggered after the cache is being checked.
That being said, stopping the find operation is possible by providing custom results, not by returning data, but by setting it via Query::setResult(), which expects an instance of \Cake\Datasource\ResultSetInterface.
An example would be:
$results = [];
$resultSet = new \Cake\Datasource\ResultSetDecorator($results);
$query->setResult($results);
$event->stopPropagation();
That would make the query return an empty result set (ResultSetDecorator is just a collection that implements ResultSetInterface), which is the closest you can come to "stopping" the query.

Related

How to update Radis for dynamic values?

I am working with some coaching using Redis in Nodejs.
here is my code implimentation.
redis.get(key)
if(!key) {
redis.set(key, {"SomeValue": "SomeValue", "SomeAnohterValue":"SomeAnohterValue"}
}
return redis.get(key)
Till here everything works well.
But let's assume a situation where I need to get the value from a function call and set it to Redis and then I keep getting the same value from Redis whenever I want, in this case, I don't need to call the function again and again for getting the value.
But for an instance, the values have been changed or some more values have been added to my actual API call, now I need to call that function again to update the values again inside the Redis corresponding to that same key.
But I don't know how can I do this.
Any help would be appreciated.
Thank you in advanced.
First thing is that your initial code has a bug. You should use the set if not exist functionality that redis provides natively instead of doing check and set calls
What you are describing is called cache invalidation and is one of the hardest parts in software development
You need to do a 'notify' in some way when the value changes so that the fetchers know that it is time to grab the most up to date value.
One simple way would be to have a dirty boolean variable that is set to true when the value is updated and when fetching you check that variable. If dirty then get from redis and set to false else return the vue from prior

Laravel - trouble with Eloquent Collection methods such as last()

I have a variable $courses that in my debugger is shown as type App/Courses
In the model, there is a one to many relation and I retrieve these related items in the model and then access as $courses->relateditems
In the debugger, $courses->relateditems is shown as type Illuminate/Database/Eloquent/Collection
Ok, all makes sense.
I want to get last item in the $courses->relateditems collection. So I try
$courses->relateditems->last()->startdate
But this is not returning the value that I know exists. And when I evaluate the expression $courses->relateditems->last() in the debugger I get this in my laravel.log:
Symfony\Component\Debug\Exception\FatalErrorException: Cannot access self:: when no class scope is active in /app/Courses.php:68
I am just not sure what is going on. I know I can use DB queries to just get the data I need, but I have a model event triggering a function and that function receives the $courses object/model (or however we name it) and I am just trying to get this working as above.
Ideas on what I am doing wrong?
thanks,
Brian
The issue here based on the error you have at the bottom of your post is a mistake in your code.
However, I think you've misunderstood how Laravel relationships work. They essentially come in two forms on a model, that of a property and that of a method.
relateditems Is a magic property that will return the result of a simple select on the relationship if one has already been performed. If one hasn't been performed it will perform one and then return it, known as eager loading.
relateditems() Is a method that returns a query builder instance for that relationship.
By calling relateditems->last() you're loading ALL related items from the database and then getting the last, which is less than optimal.
The best thing for you to do is this:
$course->relateditems()->orderBy('id', 'desc')->first();
This will get the first item return, however, since we've ordered it by id in descending order, it'll be reversed from what could be considered its default ordering. Feel free to change the id to whatever you want.

How exactly does the fetchAllIfNeeded differ from fetchAll in the JS SDK?

I never quite understood the if needed part of the description.
.fetchAll()
Fetches the given list of Parse.Object.
.fetchAllIfNeeded()
Fetches the given list of Parse.Object if needed.
What is the situation where I might use this and what exactly determines the need? I feel like it's something super elementary but I haven't been able to find a satisfactory and clear definition.
In the example in the API, I notice that the fetchAllIfNeeded() has:
// Objects were fetched and updated.
In the success while the fetchAll only has:
// All the objects were fetched.
So does the fetchAllIfNeeded() also save stuff too? Very confused here.
UPDATES
TEST 1
Going on some of the hints #danh left in the comments I tried the following things.
var todos = [];
var x = new Todo({content:'Test A'}); // Parse.Object
todos.push(x);
x.save();
// So now we have a todo saved to parse and x has an id. Async assumed.
x.set({content:'Test B'});
Parse.Object.fetchAllIfNeeded(todos);
So in this scenario, my client x is different than the server. But the x.hasChanged() is false since we used the set function and the change event is triggered. fetchAllIfNeeded returns no results. So it isn't that it's trying to compare this outright to what is on the server to sync and fetch.
I notice that in the request payload, running the fetchAllIfNeeded is sending the following interesting thing.
{where: {objectId: {$in: []}}, _method: "GET",…}
So it seems that on the clientside something determines whether an object isNeeded
Test 2
So now, based on the comments I tried manipulating the changed state of the object by setting with silent.
x.set({content:'Test C'}, {silent:true});
x.hasChanged(); // true
Parse.Object.fetchAllIfNeeded(todos);
Still nothing interesting. Clearly the server state ("Test A") is different than clientside ("Test C"). and I still results [] and the request payload is:
{where: {objectId: {$in: []}}, _method: "GET",…}
UPDATE 2
Figured it out by looking at the Parse source. See answer.
After many manipulations, then taking a look at the source - I figured this out. Basically fetchAllIfNeeded will fetch models in an array that have no data, meaning there are no attribute properties and values.
So the use case would be you have lets say a parent object with an array of nested Parse Objects. When you fetch the parent object, the nested child objects in the array will not be included (unless you have the include query constraint set). Instead, the pointers are sent back to clientside and in your client, those pointers are translated into 'empty' models with no data, basically just blank Parse.Objects with ids.
Specifically, the Parse.Object has an internal Boolean property called _hasData which seems to be toggled true any time stuff like set, or fetch, or whatever gives that model attributes.
So, lets say you need to fetch those child objects. You can just do something like
var childObjects = parent.get('children'); // Array
Parse.Object.fetchAllIfNeeded(childObjects);
And it will search for those children who are currently only represented as empty Objects with id.
It's useful as opposed to fetchAll in that you might go through the children array and lazily load one at a time as needed, then at a later time need to "get the rest". fetchAllIfNeeded essentially just filters "the rest" and sends a whereIn query that limits fetching to those child objects that have no data.
In the Parse documentation, they have a comment in the callback response to fetchAllIfNeeded as:
// Objects were fetched and UPDATED.
I think they mean the clientside objects were updated. fetchAllIfNeeded is definitely sending GET calls so I doubt anything updates on the serverside. So this isn't some sync function. This really confused me as I instantly thought of serverside updating when they really mean:
// Client objects were fetched and updated.

How to use model events with query builder in laravel

I'm using model events such as static::saving, static::saved, etc in my models' static function boot method, and that works great when users save new posts, but when I do something like this:
$post::where('id', $post_id)->update(array('published'=>1));
Updating in this way does not run those model events. My current solution is to just not use this method of updating and instead do:
$post = Post::find($post_id);
$post->published = 1;
$post->save();
But is there any way to make the model events work with the first example using query builder?
Model events will not work with a query builder at all.
One option is to use Event listener for illuminate.query from /Illuminate/Database/Connection.php. But this will work only for saved, updated and deleted. And requires a bit of work, involving processing the queries and looking for SQL clauses, not to mention the DB portability issues this way.
Second option, which you do not want, is Eloquent. You should still consider it, because you already have the events defined. This way you can use also events ending with -ing.

DbEntityValidationException but data is Valid — how to debug?

I'm getting a DbEntityValidationException from a controller method that's trying to set the boolean IsVisible on an entity it retrieves from the DB. It's responding to an AJAX post from a change in a tick box on the page. This code used to work.
var targetClass = db.Classes.FirstOrDefault(x => x.ID == cid);
targetClass.IsVisible = true;
db.SaveChanges();
This results in DbEntityValidationException with the following errors:
The SchoolYear field is required.
The TuitionPlan field is required.
When I step through this code both targetClass.SchoolYear and targetClass.TuitionPlan are valid.
Question is, how do I figure out why EF thinks these fields are missing?
EDIT: This may have to do with (too) lazy loading... If I use both of the "missing" fields, the error goes away. Probably nothing more worrisome than not knowing why a serious problem just went away.
var targetClass = db.Classes.FirstOrDefault(x => x.ID == cid);
targetClass.IsVisible = value;
int x = targetClass.TuitionPlan.ID;
x = targetClass.SchoolYear.ID;
db.SaveChanges();
I really need someone to explain what's going on here, and how I should prevent this in the future.
Thanks for insight,
Eric
I don't think it is a good idea to validate navigation properties against null. A navigation property set to null means that there is not a related entity (the condition you want to validate) but can also mean that the relate entity was just not loaded. Now, sending an additional query to the database just to validate it is there seems to be an overkill and may cause performance problems (first and foremost you may be sending a lot of queries to database, second (unless you load the entities as not being tracked) you start tracking many more entities that you actually need track). Also note that for the above reasons validation disables lazy loading until validation is complete. This is probably the reason you see the errors even though in your app lazy loading is enabled. During validation it will be disabled and accessing the navigation property will not load the related entity. If you want to validate whether a related entity exists you can use foreign keys. Note that it won't require loading the related entity and should be relatively easy to do.

Resources