Use retrieved value from internal query to query with Laravel Eloquent - laravel

The value I need for the now() query is the timezone from the Group model, I'm just not sure how to get it within the query.
I would like to use $reminder->group->timezone value instead of hardcoding the value in now(). Any help would be greatly appreciated.
$reminders = Reminder::with('group','appointment')
->where('reminder_datetime', '<', Carbon::now('America/New_York')) --> Use $reminder->group->timezone value instead of hardcoding the value
->get();

The query will not be executed until you call the get method.
However, you need the query result of the group of reminder to reach the timezone in order to call the now method of Carbon inside PHP.
Because you need the timezone before retrieving the query results, that won't work.
Instead, you can get the reminder results without the where method - with timezones - and than filter the Eloquent Collection as you want in your method.

Related

Laravel eloquent not retrieving results based on boolean column

I have 33 results on my DB where this boolean field (resolvido) is showing zero, if I run the SQL query it retrieves the results, however in the model the collection always comes empty.
If I change to Model::where('resolvido',1)->get(), I do get the correspondent results, however the Model::where('resolvido',0)->get() or the Model::where('resolvido',false)->get() or even using the query builder and raw sql, the collection never picks up those 33 results where resolvido = 0.
I've also tried in Tinker and it always comes up empty.
Migration:
$table->boolean('resolvido')->nullable();
On DB comes up as TINYINT
Any tips on what it might be?
Thanks in advance
Naturally, there is no boolean data type for MySQL but rather uses TINYINT (0 or 1) for this.
Laravel's query builder, allows using boolean in the where clause. You might want to try these:
Model::where('resolved', true)->get();
Model::where('resolved', false)->get();
Since you've set the resolved column in the DB as nullable, you might also want to try:
Model::where('resolved', null)->get();
If you don't want that behavior use $table->boolean('resolved')->default(false) instead
Try this
Model::where('resolved', null)->get()
or
Model::where('resolved', '')->get()

DayOfWeek in LINQ query

I have a simple list of integers that represent days of week. I am trying to check if Date property of my entity is in the selected days of week. But if I try to pass it in query that targets database like this:
query.Where(e => selectedDaysOfWeek.Contains((int)e.Date.DayOfWeek));
I got the exception:
The LINQ expression ... could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().
If I on the other hand, first execute query by calling ToList() (for example) and then add the same where condition on resulting list, it works:
var items = query.ToList();
items = items.Where(e => selectedDaysOfWeek.Contains((int)e.Date.DayOfWeek)).ToList();
Although in my case this is acceptable, I would like to fetch less items from the database. Is there a way to check DayOfWeek when querying db as was my initial intent?
You are accessing the DayOfWeek property from a DateTime reference in the query.
Entity Framework "doesn't know" how to translate that to SQL thus in the first piece of code you getting an exception.
And in the second piece it is working after you have fetch all of the data from database at the .ToList() call, and the .Where filtering is happening in the memory.
If you wish to implement that logic on the database side, you will have to write your own SQL statement.

Sum of the values of a particular user for a particular month of a particular year

I have a table with time stamp, user id, value. I am trying to get sum of the values of a particular user for a particular month of a particular year. This is what I am using:
$data = Laborhrs::all()->where('employee','7')->sum('value');
This is giving me sum of whole data for employee#7. I am looking to get sum of a particular month of a particular year. Say Sum of values of October 2018. What am I missing?
You forgot to add a condition for the year and month, and you don't need to use all() method.
$sum = Laborhrs::where('employee','7')
->whereMonth('timestamp_column_name', 10)
->whereYear('timestamp_column_name', 2018)
->sum('value');
In addition: I saw your several posts, and I think, you don't understand how laravel eloquent and collections work.
All() method returns collection with all results from database, and then you filters them trough collection (I saw it not first time). It is very slow solution.
Better to use conditions with get() (get() should go after conditions), for example:
$data = Laborhrs::where('employee','7')->get();
It will return collection with results that you need, and you don't need to filter them after getting from database. It will be work much faster.
In that situtation you don't need all() and get() methods at all. Eloquent has sum() method, that will calculate sum in database and return value.

query to get only one item from target column in Laravel

Is there any query to get only one item from target column? below didn't working?
App\Job::whereNotNull('deleted_at')->pluck('customer_name')->first()
I wish to get just one item name from 'customer_name'
Now Laravel 5.6 using...
When using eloquent, using first will give you a single item, the first record matching your query. You can then access the property on that item:
// This will give you an instance of App\Job (or null)
$job = App\Job::whereNotNull('deleted_at')->first();
// You can then access the customer_name property on the object
$job->customer_name;
If you only want to retrieve that single column when you run your query, you can pass an array of columns to first.
App\Job::whereNotNull('deleted_at')->first(['customer_name']);
Assuming you're using the SoftDeletes trait in your model, your query will automatically have an additional check added to all of your queries to ensure that deleted_at is null. So when you're doing ->whereNotNull('deleted_at') you're adding an additional clause to ensure records are not null as well, so you won't have any records being returned.
If you want to look only at deleted records, you can use onlyTrashed():
App\Job::onlyTrashed()->first();
There is a built-in method for this: value('field')
App\Job::whereNotNull('deleted_at')->value('customer_name');
Docs: https://laravel.com/docs/5.6/queries, look for "Retrieving A Single Row / Column From A Table"
If you meant only one field but still as rows, you can use ->select('field') instead.
And since you want only trashed items, you can use ->onlyTrashed() instead of the not null check.
Soft deleting documentation: https://laravel.com/docs/5.6/eloquent#deleting-models
Try like this:
$job = \App\Job::selectRaw('customer_name')
->whereNotNull('deleted_at')
->first();
And use it like $job->customer_name

CouchDB View with Multiple Parameters

I have a database that has an id column and a ts column. I need to be able to pass in the id and a start time and end time to retrieve all the values during the specified period. Can I do this with a view, or do I need the view to return all of the values that match the id? My concern is that I will be returning and parsing a lot more data than I really care about. Here is the format of my DB from my current view, which simply returns everything that matches the id...
{"id":"62db2aa3472dce80b1f2193fc21d52fd","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d52fd","_rev":"1-6aadd58f4f5dabacf6f4f638396246d0","id":"A-Meter-KW","ts":1437969600000,"tz":"New_York","val":"191kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d5100","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d5100","_rev":"1-71155153c0f03c49b02850bee5535e22","id":"A-Meter-KW","ts":1437968700000,"tz":"New_York","val":"190kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d45d7","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d45d7","_rev":"1-661511616958d45fdff3307600d2a9ed","id":"A-Meter-KW","ts":1437967800000,"tz":"New_York","val":"189kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d3c23","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d3c23","_rev":"1-4e97cfc6cb97ddc65f04efd9043b3abd","id":"A-Meter-KW","ts":1437966900000,"tz":"New_York","val":"188kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d2e35","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d2e35","_rev":"1-120298e95c9d2b4b9cdf438836b6c0c0","id":"A-Meter-KW","ts":1437966000000,"tz":"New_York","val":"187kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d22b0","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d22b0","_rev":"1-61e55d02bd8f0c601274b904f46c9f34","id":"A-Meter-KW","ts":1437965100000,"tz":"New_York","val":"186kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d1ce2","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d1ce2","_rev":"1-b4fe80563c70a40981e293af9c6a87b3","id":"A-Meter-KW","ts":1437964200000,"tz":"New_York","val":"185kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d1ccc","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d1ccc","_rev":"1-bdf1881c4270e68e7a7ed90a1d945228","id":"A-Meter-KW","ts":1437963300000,"tz":"New_York","val":"184kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d1303","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d1303","_rev":"1-404d5934fc882aa36e6d355d9a3485ae","id":"A-Meter-KW","ts":1437962400000,"tz":"New_York","val":"183kW"}},
{"id":"62db2aa3472dce80b1f2193fc21d0941","key":"A-Meter-KW","value":{"_id":"62db2aa3472dce80b1f2193fc21d0941","_rev":"1-64288d1c98e9b93aa6c546acb1e02078","id":"A-Meter-KW","ts":1437961500000,"tz":"New_York","val":"182kW"}}
...
... my current query is http://localhost:5984/hist/_design/hist/_view/byId?key=%22A-Meter-KW%22&descending=true. I'd like to passing a start and end time as well, something like http://localhost:5984/hist/_design/hist/_view/byId?key=%22A-Meter-KW%22&descending=true&start=1437963300000&end=1437966000000 but cannot figure out how to do this.
EDITED:
In order for Couch to match your query all the data (eg:A-Meter-KW and date) must be in the key, emitted by the view. So I think you might do something like:
emit([key,year,month,day],doc._id)
Then you can use the parameters startkey and endkey to filter the results properly.
Reference: http://guide.couchdb.org/draft/views.html#many
Side consideration: I would not use an "id" property inside my documents, because it could get easily confused with the "_id" (compulsory) one.

Resources