How would you write a complex query in laravel 5? - php

Hello guys I wonder if this query I wrote with laravel's syntax is actually make sense.
What I am trying to do: I got two tables. One is users table. Second is the dependent table for users. its called user's_thoughts. I want to pull the top best results of posts from users table. and this top results are based on how many likes that particular post had. This like column is in user's_thoughts table.
Here is what I have put together for this:
$results=DB::table('users')->join('user_thoughts', 'users.id', '=', 'user_thoughts.user_id')->select('users.post_id', 'users.post_title', 'users.posts', 'user_thought.like')-get();
Now, after this query which selects from both tables, I am going to see which post had the highest amount of likes.
$count = DB::table('user_thoughts')->count('likes');
$highest = DB::table('user_thoughts')->max('$count');
Now, here I would loop the results out.
$show = foreach ($highest as $cherrypicked => $topones) {
echo $topones;
}
Have I followed this correctly? What do you think?
Thanks.

Related

Eloquent query based on presence of key in relationship group

So this one has kinda given me a mental run around. I have Rows, Users, and RowActivity models. Each time a user interacts with a row, it generates a single line in the row activity table saying what status the user changed. Each row can have 3-8 activity entries with a single user reference per line. So my question is this: I want to analyze the rows that particular users have interacted with. So I'd like to search for user A and get all the rows they've touched. But the only way to do that is to query the RowActivity table.
So the query would essentially be this:
Row::whereHas('rowActivity')->whereWithin(Collection of RowActivity, user_id = requested-user)->get();
I know that I can go the long way and query the RowActivity::where('user_id', $requestedUser) and then get all the other row activities based on the related row_id of that those results, but I feel there's a clean way that I can't figure out.
Just for clarification, the row activities are used to generate reports about which users changed the status of the row and how long the duration between the changes are. So I need to get all the activities associated with a row as well as all the rows that a user has touched so that I can analyze how long their portion of that interaction took.
If I need to do this as a multilevel query, so be it, I don't have an aversion to that, I just want to make sure my queries are pristine. If I did it as multi-level, it would look something like this:
$ra = RowActivity::where('user_id', $requestedUser)->pluck('row_id');
$rows = Row::with('rowActivity')->find($ra); //get all rows and their associated activities based on the plucked row id from query 1
You can do that within whereHas(). I hope that's what you want
Row::whereHas('rowActivity', function($query) use($requestedUser) {
$query->where('user_id', $requestedUser);
})->get();

SQL JOIN statement with two fields equal to one [CodeIgniter]

I am trying to put together a SQL statement which pulls the names of employees that have a certain title and how many labor hours that they currently have in total for a total of the current week. I am working with two different tables, so I assume that I would need to use JOIN in this case, however my dilemma is that I would need to join two fields from TABLE A to one field on TABLE B. Is this possible?
See below for my code (so far):
public function get_all_techs_with_hours()
{
// get all technicians
$this->db->select('*');
$this->db->from('employees');
$this->db->where('role', 'Body Technician');
$this->db->or_where('role', 'Paint Technician');
$this->db->or_where('role', 'Combo Technician');
$query = $this->db->get();
return $query;
}
In this case, employees is TABLE A and jobs is TABLE B. I need to JOIN TABLE B to TABLE A based on jobs.body_tech matching employees.first_name and employees.last_name. Atleast, I think I do. I'm sure I'm going about this the hardest approach possible, but I can't seem to find any helpful manual to learn how to do this. In the end, all I would like to do is combine all hours for each technician and add to the same array using two different tables.

Codeigniter check if one columns items present in another column

I have been trying to figure out how to check if any of one column's items present in another column in Codeigniter....
I have Bike,Car,Bus in a column(Vehicles) in a table1...
I also have Bus,Helicopter,Ship,Car in a column(Interested) in table2..
How to check if any of table2 interested column's items present in table1 vehicles column...
I tried like this...
$query = $this->db->get('table2');
foreach($query->result() as $row)
{
$a = explode(',', $row->interested);
$this->db->where_in('Vehicles', $a);
$query = $this->db->get('table1');
foreach($query->result() as $row2)
{
echo $row2->ID;
}
}
Could it be done ?? Please Help me... Thanks in advance....
It is very hard to help you without seeing the tables and how you are relating one to the other (such as user_id).
What you should do is two queries. One query to get the data from table 1 of the vehicles you are interested in. Then run through the result set and create a simple array of those vehicles in php. Then do a second query using where_in to select all the rows that are in the chosen vehicles array.
Your method is bad because the number of db queries depends on the size of the result set of your first query. You might find your code trying to do hundreds of database queries.
If you show a diagram of your tables, I could write some example code for you.
Here are the docs for where_in: https://www.codeigniter.com/user_guide/database/query_builder.html#CI_DB_query_builder::where_in

Retrieving most liked comment using two tables

I have two tables, one for comments and another for likes, each row In the likes table shares the same comment ID in the comment table so I can link them together. However I'm only relating them through a foreach.
#foreach ($getNotesAll as $getnotes)
<?php
$upvoteCount = $getNoteVotes->where('noteUniqueID', $getnotes->noteUnique)-
>where('like-type', 'upvote')->count();
?>
#endforeach
Using
$getNoteVotes = noteLikes::all()->where('type', 'upvote');
$getNotesAll = Notes::orderBy('created_at','asc')->paginate(10);
I'm at a point where I need to get the most liked comments, so I'll have to query the like table to request rows with the most repeating comment ID's in descending order, then querying the Comments tables with the Comment Id's from the like query. I can't quite get my head around this without using a foreach loop, though I think this is achieved using models, but any guidance would be appreciated
Try something like this:
DB::table('commentsTable')
->join('likesTable', 'commentsTable.id', '=', 'likesTable.comment_id')
->select('commentsTable.tittle',DB::raw("count(likesTable.comment_id) as count"))
->groupBy('likesTable.comment_id')
->orderBy('likesTable.comment_id','asc')
->get();

Cakephp - get database data from not associated models

I wanted to ask, how can i get data from one table and use this in other find.
For example, i have films table.
I want to get highest rated 3 films. Result should return 3 ID's.
Now, i want to create other query from not associated table, and pass this 3 ID's as "conditions" to find data in other table.
I dont want to use associations, because, data is stored in many databases, and this is problematic.
Thank You.
Once you've got your film IDs you can use in to filter the results from your other Model:-
$filmIds = ['32','55','75'];
$query = TableRegistry::get('Model')->find()
->where(function ($exp, $q) use ($filmIds) {
return $exp->in('film_id', $filmIds);
});
// WHERE film_id IN ('32','55','75')
Check out the docs section on advanced conditions.
If you need to get your film IDs into the correct format (i.e. that shown in the example code) you can use Hash::extract() on the results from your previous query.
if your cakephp version 3.x you can use subqueries in fairly intuitive way
$films = TableRegistry::get('Films')->find('highestRated')
->select(['id'])
->limlt(3);
$query = $related->find()
->where(['id' => $films]);
Subqueries are accepted anywhere a query expression can be used. For example, in the select() and join() methods. http://book.cakephp.org/3.0/en/orm/query-builder.html#subqueries

Categories