Call to a member function where() on float in laravel 5.4 - laravel-5

Its not duplicate question. Sorry for such type of starting.
$sum = DB::table('tasklists')->sum('list_weight')->where('task_id','10');
it show me Call to a member function where() on float. I am trying to find out the reason ......

Use sum after the where as you need to condition first and take output later.
What happens is when you call a function on DB which generates a output or query result, The facade runs the query and gets you the output.
So, in your case when you call sum the query prepared before sum is get executed and sum returns the sum of results i.e. float.
Now, you are trying to access where method on a float(which is output of the sum) not on the query itself.
That is why you are getting the error.

Related

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.

Make a method which generate result for once (first time) and return while it called as it store at the first time

I am new in codeigniter. I have a little bit problem. Like, a function which calls for many times and has a complex query. This function will generate the result for the first time and store the result in a variable . when I will call this function it will return its stored result.
Suppose I have a method like
public function add_sum(){
$a=2;
$b=3;
return c=$a+$b;
}
This function will generate the result for the first time, and when I will call this function after first time.
$a=2;
$b=3;
return c=$a+$b;
this code will not be executed. without this block it will return 5. Hope guys you got my point. Calling function is..
public function test(){
$this->add_sum();
}
Thank you...
Sessions aren't for storing big amounts of data. In fact, depending on your system, it may result in issues. Cookies are similar.
If your query is big but returns something small like as you suggested a number, then it is perfectly fine to store it in a session variable. If it returns something big like a large array, then you could consider using some sort of caching mechanism. Codeigniter has an in-built one for database caching, whose methodology I don't necessarily believe in. But this is generally how you use it if you just want to cache a few queries: https://www.codeigniter.com/user_guide/database/caching.html#function-reference otherwise you can just turn db caching on in database.php (don't do this unless you thoroughly understand the consequences).
You could consider writing/read the results from a file, but you would have to benchmark it to see if it is faster than just performing the SQL operation.
Now to answer your specific question:
public function test(){
if ($this->session->has_userdata('test_response')) {
return $this->session->test_response;
}
$sum = $this->add_sum();
$this->session->set_userdata('test_response', $sum);
return $sum;
}
as you can see, on the first run the conditional statement will eval to false, add_sum will run, and its contents will be assigned to a session variable. on subsequent runs, this variable will be retrieved from the session immediately.

`r.row` and `r.contains ` in nested queries not working

Trying to add a new field inside of a document using a field from another table. I first tried to use r.row
r.db('client').table('basic_info').filter({name:'Andre Pastr'}).update({teacher_name: r.db('teacher').table('basic_info').contains(r.row('name').eq('Nicholas Derma')).pluck('id')});
and it returned the message:
e: Cannot use r.row in nested queries. Use functions instead in:
r.db("client").table("basic_info").filter({name: 'Andre Pastr'}).update({"teacher_name": r.db("teacher").table("basic_info").contains(r.row("name").eq("Nicholas Derma")).pluck("id")})
^^^^^
so then after finding this [vague entry][1] in the github issue log I just decided to just change the syntax of my query and run:
r.db('client').table('basic_info').filter({name:'Andre Albuquerque'}).update({teacher_name: r.db('teacher').table('basic_info').filter({name: 'Nicholas Chadwick'}).pluck('id')});
That returned the error message:
: Could not prove argument deterministic. Maybe you want to use the non_atomic flag?
Three inter-related questions: How might I use contains to run such a query? What am I doing wrong with this second query? Why doesn't r.row work in the first query?
You can't use r.row in the first query because it's ambiguous whether it should be bound to contains or to update. (We could define which one it's bound to, but it's very confusing for people because most people haven't memorized all the terms that could possibly bind r.row, so it's easier to force people to name their variables in ambiguous cases.)
You have to specify the non_atomic flag because the function you're passing to update can't be applied atomically (since it isn't deterministic). The way you wrote it, it will be executing a table fetch for every row in the original filter.
You probably want to write something like this instead:
r.table('basic_info').filter({name: 'Nicholas Derma'}).pluck('id').do(function(nderma) {
return r.table('basic_info').filter({name: 'Andre Pastr'}).update({teacher_name: nderma);
})
You should consider creating a secondary index on name and using getAll instead of filter if you run this query often.

Why does Laravel Controller needs (integer) cast in Homestead, but not in production server

(integer) cast must be done in Homestead for Controller parameter
I am having a hard time searching for the cause of a discrepancy between my local dev environment (Homestead) and the hosted one.
I define a route like this:
Route::get('group/{id}/data', 'GroupDataController#index');
And the code in the Controller looks like this:
public function index($id)
{
return Grouping::all()->where('group_id', $id);
}
Which works fine in production (hosted env), BUT when I execute it locally it throws and empty array [] unless I modify my Controller function to look like this:
public function index($id)
{
return Grouping::all()->where('group_id', (integer)$id);
}
I have no idea of what is going on in here, and I am tired of making changes all over my Controller to make it work on both environments.
I have searched in several place, but maybe I am using incorrect tokens for my search as I have found nothing.
Any help will be really appreciated.
The problem here is that you're not using the correct set of functions.
When you call Grouping::all(), this is actually returning an Eloquent Collection object with every record in your groupings table. You are then calling the where() method on this Collection. This causes two problems: one, it is horribly inefficient; two, the where() method on the Collection works differently than the where() method on the query builder.
The where() method on the Collection takes three parameters: the name of the field, the value in that field on which to filter, and finally a boolean value to tell it whether or not to do a strict comparison (===) or a loose comparison (==). The third parameter defaults to strict. This strict comparison is why you're having the issue you are having, but I cannot explain why one environment sees $id as an integer and the other doesn't.
The where() method on a query builder object will actually add a where clause to the SQL statement being executed, which is a much more efficient way of filtering the data. It also has more flexibility as it is not limited to just equals comparisons (the second parameter is the comparison operator for the where clause, but will default to "=" if it is left out).
You have two options to fix your issue. You can either pass in false as the third parameter to your where() method in the current code (bad), or you can update the code to actually filter using the query instead of filtering on the entire Collection (good).
I would suggest updating your code to this:
public function index($id) {
return Grouping::where('group_id', '=', $id)->get();
}
In the above code, Grouping::where('group_id', '=', $id) will generate a query builder object that has the given where clause, and then get() will execute the query and return the Collection of results.
I marked #patricus (thanks you, so much!) as the correct answer, for he really pointed me in the right direction to understand that there are some keywords that work differently under different contexts (like get()), but I will also point out, how my 2 confusing points were solved in my case:
The difference in my code between production and Homestead development environments was solved by pointing my Homestead to the production database. I am not sure what was the difference (maybe collation or table format), but it gave me a quick out.
I was trying to filter a list of elements in the database but I was constructing it with the wrong logic for Laravel.
To clear what I refer to in the second point, I was using this code:
Grouping::all(['id', 'name_id', 'product_id', 'ship_id'])->where('name_id', '=', $id);
I thought this could work, because it would be selecting all items, with the selected columns, and then filter those with a where clause. But I was wrong, since, as I found out later, the correct way of writing this is:
Grouping::where('name_id', $id)->select('id', 'name_id', 'product_id', 'ship_id')->get();
This is because I forgot completely that I was assembling the query, not writing the actions I expected the program to do.
This second syntax has more logic, since I specify the filter, then put the columns over what was filtered, and finally execute the query with the get() clause.
Of course, it can also be written the other side around for clearer fluent reading:
Grouping::select('id', 'name_id', 'product_id', 'ship_id')->where('name_id', $id)->get();

CodeIgniter and MongoDB : query

I'm trying to query in MongoDB using PHP/CodeIgniter but I can't find a solution...
I have a first query in "function1" where there is
$this->mongo_db->where("category" => getCatID("games");
And in my second function "getCatID" I have
return $this->mongo_db->select('_id')->where("name" => $name)->get('Category');
But it seems that the second function continue on the first query of function1.
I'm using this library...
I assume your first code snippet was intended to be:
$this->mongo_db->where("category", getCatID("games"));
// or…
$this->mongo_db->where(array("category" => getCatID("games")));
I've not used this library, but from perusing the source code, it looks like all query criteria set by where() is accumulated in an internal $wheres property on the Mongo_db class. This only gets cleared by the private _clear() method, which is called from the following public methods:
get()
count()
update()
update_all()
delete()
delete_all()
add_index()
remove_index()
remove_all_indexes()
Any time either of those terminating methods are called, $wheres will be reset. Likewise, if those methods aren't called, older criteria may bleed into your next criteria. In your case getCatID() may be clearing out earlier criteria. PHP is going to execute getCatID() before invoking the where() method in which it's an argument, so I'd expect that outer where() call to see an empty $wheres array.
One solution would be to call getCatID() on its own before building your second query. Alternatively, you could clone the Mongo_db instance to ensure that each query is built independently.

Resources