I'm making a reservation system for a media library, the goal is to book a room for a certain time. There are 8 time slots in total with a start_time & end_time.
The user has to fill in a date and I have to check what time slots are still available at that date.
So, for example.. there can only be one row in the database that contains date: 2016-12-08 time_slot: 3.
How do I check if this row exists in my database using Eloquent?
You can do laravel model query to check if there is any results, like this :
$data = Model::where('date','2016-12-08 ')->where('time_slot', 3)->count();
Assuming you have a slot table with the fields you are sharing. Slot table: id, date, time_slot...
$your_date = 2016-12-08;
$date = date('Y-m-d', strtotime($your_date));
$time_slot: 3;
$slot = Slot::where('date', $date)->where('slot', $time_slot)->first();
if($slot == null) {
// book can be made
}
else {
// already booked
}
You can take the help pf Laravel Query Builder's exists for checking the if the fields are present in database like this:
$exists = Model::whereDate('date', '2016-12-08')
->where('time_slot', 3)
->exists();
Here exists returns a boolean value, which depends upon the existence of the query above!
Hope this helps!
Related
I have 2 databases(one in mySql and the other one in MongoDB) in my project and I need to perform a query like this
public function getPosts() {
$user = Auth::user();
$follow = DB::connection("mongodb")
->collection("followers")
->where("user_id", $user->id)->get();
/*$res = DB::select("
SELECT *
FROM posts
WHERE user_id = ? OR user_id IN
(SELECT user_id from $follows)
ORDER BY created_at DESC", [$user->id, $user->id]);
*/
return response()->json($res);
}
This is a query which returns the posts from the logged user and from people the user follow
The followers table (the one in MongoDB) contains "user_id" and "follows_id"
The commented line is the original query (every table in one single database on mySql
Thank you
Edit: I solved through a query in mongodb, then I edited the result to get an array which I incorporated into the sql query through orWhereIn Thank you for your answers :)
I don't think so... you may try a true multimodel database such as Oracle XE (it's free) to achieve your goal here...
I have following table prpaps 1 in mysql database. I am able to display all the results in view of codeigniter. But how can i display count for particular year.For example 2016 records (6), 2017 records (2).How can i display count author wise in a year. For example in 2016,aks(2),amit(1),pradeep(3),sanjay(1), shefali(2),arjun(2).I tried a lot but not able to get desired result.
I will be very much grateful if any body help me to write command for
Controller
public function pagination()
{
$this->load->model('Sample_model');
$config['base_url'] = 'http://localhost/test/index.php/welcome/pagination/';
$config['total_rows'] = $this->Sample_model->count_rows('prlapps');
$config['per_page'] = 20;
$config['num_tag_open']='   ';
$config['next_tag_open']='   ';
$config['last_tag_open']='   ';
$config['cur_tag_open']='   ';
$config['prev_tag_open']='   ';
$this->pagination->initialize($config);
$data['table'] = $this->Sample_model->get_limited_data(20, $this->uri->segment(3));
$data['view']='pagination_view';
$this->load->view('load_view',$data);
}
view
<?php
echo $this->table->generate($table);
echo $this->pagination->create_links();
?>
The solution here is to break this data into a separate authors table. You would end up with the following tables:
Books table
Authors table
Book_Authors_link
Each Author gets their own ID and each book gets its own ID - you then combine them in the Book_Authors_link table and can then join on that table and use Mysql GROUP BY and COUNT(*) to see how many authors did what in each year.
I've got a use case where I need to query for Appointment records based on their created_at or their start_on values. There are two types of appointments: 'Estimate' and 'GLA (go look at)', represented by a type field with values 0 and 1.
If the appointment is of type Estimate, the query needs to use the start_on field - and if the appointment is a GLA, the query needs to use the created_at field, as GLA's are not scheduled and don't have start_on values.
Right now, I'm querying the data using a Rails scope to filter down properties who've had their last appointment from and to a certain date like so (the following shows 'from'):
scope :last_appointment_from, ->(date, type) {
query = joins(:appointments)
query = query.where('appointments.start_on = (
SELECT MAX(appointments.start_on)
FROM appointments
WHERE appointments.property_id = properties.id)')
query = query.where('appointments.start_on >= ?', date)
query
}
But this only queries the start_on value.
I've tried looking into doing GREATEST(MAX(start_on), MAX(created_at)) - but then I'm not sure how to know which field to know to use in the where('events.start_on >= ?', date) part.
After typing this out, I thought of another possible workaround - to just create another database field that gets updated with the corresponding date on an active record callback based on what type of Appointment it is, called query_field or something (and run a script to set that value for all existing records) - and that way I can just query on that one field?
Any thoughts/help is greatly appreciated!
Since you already have a type field, it could be a use case for STI, i.e. same SQL schema for the model but different behavior on the ruby side.
Note the "type" field may already be causing issues with rails that you may not have considered as this field generally is reserved specifically for Single Table Inheritance STI in rails.
If you use STI you could just write an accessor that pulls the correct field from the database and presents it for each model.
I think this approach should work assuming that no appointment should have a created_at before its start_on unless it is GLA
scope :last_appointment_from, ->(date, type) {
query = joins(:appointments)
query = query.where('GREATEST(appointments.start_on, appointments.created_at) = (
SELECT GREATEST(MAX(start_on), MAX(created_at))
FROM appointments
WHERE appointments.property_id = properties.id)')
query = query.where('GREATEST(appointments.start_on, appointments.created_at) >= ?', date)
query
}
I'm not very good with Rails but for the pure MySQL you could use a where like this:
WHERE (
(appointments.created_at > date
AND appointments.type = 1)
OR
(appointments.start_on > date
AND appointments.type = 0)
)
I am writing a django application where I have to pick only one row from and exclude the rest of them from multiple rows containing same date in their datetimefield column.
My model is:
class Model(models.Model):
user_id = models.IntegerField()
datetime = models.DateTimeField()
I want to select only one user from each single date. Here is how i select all rows:
data = Model.objects.all()
How do I select only one user from each date in datetimefield?
You can try this,
data = Model.objects.all()
date_list = list(set([element.datetime.date() for element in data]))
for date in date_list:
obj = Model.objects.filter(datetime__date=date).first()
if isinstance(obj, Model):
user_list.append(obj.user_id)
return user_list
I hope this will help.
If you want select one user per each datetime you may use this
data = Model.objects.all().distinct('datetime')
If you want select one user per each date you may use this
data = Model.objects.all().extra({'date': 'date(datetime)'}).distinct('date')
date - is a SQL function may depend of sql server that you use
or you may use TruncDate if you use django 1.10+
data = Model.objects.all().annotate(date=TruncDay('datetime').distinct('date')
Without distinct you may use this hack:
data = Model.objects.all().extra({'date': 'date(datetime)'}).values("data").annotate(Max("user_id"))
I built up a pivot table containing ids of tables I want to associate. When I have the id of a specific item, I now want to get the latest entry of this item saved in the pivot table. For example:
Table 1: Tickets
Table 2: Status
Table 3: Ticket_Status (Pivot)
If I add a new entry to the pivot table, I would have something like this:
Pivot
ticketId, statusId
1, 2
1, 3
2, 1
Now I want to receive the latest status in the pivot for Ticket Id 1 for example, so I expect to receive statusId 3 for ticket 1. But how do I do this in Laravel?
Creating the entries for the pivot table works:
public function attachDispatchStatus($id) {
$this->status()->attach($id);
$this->touch();
}
// set fields on the eloquent object and save to database
// raise event that the incident was created.
public function createDispatch($command) {
// Get BodyContent from POST Request
$this->dispatchReference = $command->dispatchReference;
$this->incidentReference = $command->incidentReference;
// Create new Dispatch
$dispatch = Dispatch::create(array(
'dispatch_reference' => $this->dispatchReference,
'incident_reference' => $this->incidentReference
));
$dispatchStatus = DispatchStatus::where('status', '=', 'processing')->first();
$dispatch->attachDispatchStatus($dispatchStatus->id);
return $this;
}
Why don't you use the updateExistingPivot($roleId, $attributes); available in Laravel 5 when editing your tickets ?
This will solve your problem and make your database lighter :)
Check Larvel Doc for some examples on pivot table.
If you don't want to make it like that (because you want to keep an historic of your input), I think you will have to add an dateTime field in your pivot table... Then, just order by date, and you will be fine.