I've been trying for several hours to make this little query work, but I cant seem to make it work.
Basically I'm trying to do a foreach from the results of the query.
This is the query I want in raw MYSQL:
SELECT id FROM albums WHERE id IN (SELECT album_id FROM user_albums WHERE user_id =".Auth::user()->id
And I tried the following:
$myAlbums = Album::whereIn('id', DB::table('user_albums')->where('user_id', Auth::user()->id)->select('album_id')->get());
But it seems like the whereIn doesnt take the array from the select correctly and it gives nothing back.
The query builder doesn't support subquery.
Break it up into two queries. Something like this. (untested)
$albums = DB::table('user_albums')->where('user_id', Auth::user()->id)->get();
// collect the album ids
$albumIds = array();
foreach ($albums as $a) {
albumIds[] = $a->album_id;
}
$myAlbums = Album::whereIn('id', $albumIds)->get();
Related
I have a nested relationship and I would like to filter them, using the result that comes from the first query run by Eloquent.
My Eloquent query is:
$entry = Entry::with([
'products.unit',
'products.area'
])->find($id);
The query log shows me that Eloquent runs this query first:
select * from entry where entry.deleted_at is null and entry.id = ? limit 1
And I would like to use its result in this second query, also run by Eloquent:
select area.*,
area_product.product_id, area_product.quota as pivot_quota,
area_product.month as pivot_month
from area inner join area_product
on area.id = area_product.area_id
where area.deleted_at is null and area_product.product_id in (?)
I would like to put a constraint inside it using the month value that comes from the first query.
Is there a way to do it using Eloquent?
I was thinking in something like this:
$entry = Entry::with([
'products.unit',
'products.area' => function ($q) {
// using month here!
}
])->find($id);
I need to make a query using 3 tables and i having some trouble with that.
I have 3 tables in my project:
projects, projects_categories and categories
projects
id_project
title
date
projects_categories
id_proj_cat
id_project
id_category
categories
id_category
name
I already made a join query but the result is a array with the same project_id showing several times.
What i need is a more efficient query that can list for each project_id a array inside, with it´s categories and names. Something like that.
I can make a separate query but im trying to achieve that in one single query.
Try this
$this->db->from("projects p");
$this->db->select("p.id_project,c.categories,c.name");
$this->db->join("projects_categories pc","pc.id_project = p.id_project","LEFT");
$this->db->join("categories c","c.id_category = pc.id_category","LEFT");
$result=$this->db->get()->result_array();
Now $result is your array.
Try this one:
$this->db->select('p.id_project,c.categories,c.name');
$this->db->from('projects p');
$this->db->join("projects_categories pc","p.id_project = pc.id_project","INNER");
$this->db->join("categories c","pc.id_category = c.id_category","INNER");
$query = $this->db->get();
return $query->result_array();
This should be a basic question, but I haven't used Mysql for a very long time and forgot all the basic stuff. So SO programmers please bear with me.
I have 2 tables like this:
Table 1 (events): here
Table 2 (users): here
I would like to select all rows in the events table where event_invitees contains a username. I was able to do this using:
SELECT * FROM meetmeup_events WHERE event_invitees LIKE '%$username%'
Now I'd like to also select the event_invitees's photo from the users table (column called user_userphoto). My attempt to this was this:
$result = mysql_query("SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
WHERE event_invitees LIKE '%$username%'
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
This gave me an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource
How can I do this? What am I missing? Can you give me some examples?
Thanks in advance! I'll be sure to accept the working answer!
You should change your mysql functions to either mysqli / PDO, although the problem seems to be the query itsef. Should be:
SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter
WHERE event_invitees LIKE '%$username%'
(the WHERE clause at the end)
Sql fiddle demo: http://sqlfiddle.com/#!2/852a2/1
Its just a matter of getting the query coded in the correct order, and you might like to make it a little more managable by using alias's for the table names
Try this :-
SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'
This of course assumes that all the column names are correct and the mu.user_username = me.event_inviter does in fact make sence because those fields are in fact equal
Additional Suggestion
You are not actually issuing the query for execution by mysql.
You have to do this :-
$sql = "SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'";
$result = mysql_query($sql);
$rows = array('mysql_count' => mysql_num_rows($result) );
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
Now in your browser using the javascript debugger look at the data that is returned. There should at least be a mysql_count field in it even if there is no 'meetmeup_user' array, and if it is zero you know it found nothing using your criteria.
I am displaying images on my website with their details, however of late the site is very slow at loading.
The main thing is this foreach loop that loops through 100 times to display 100 posts in a grid. It takes 14 seconds to run
foreach($posts as $post) {
$hashtags[] = $this->HashTagsModel->get_hashtags($post["id"]);
$author[] = $this->UserModel->get_user_details($post["user_id"]);
$comment_count[] = $this->CommentModel->get_comments_count($post["id"]);
$is_favourited[] = $this->FavouriteModel->is_favourited($post["id"]);
$is_reposted[] = $this->RepostModel->is_reposted($post["id"]);
$vote_status[] = $this->vote_status($post["id"]);
$comments[] = $this->count_comments($post["id"]);
}
How can I do this differently to make it more efficient? This worked before our websites database became massive
Any help would be appreciated,
regards,
Almost Fired
The efficient way to foreach loop query database is to not foreach query database. This is because you are allowing an unknown amount of queries to be fired off which will cause massive queueing. What if suddenly 5000 images get added, do you loop through them all? That query will take a very long time.
You have $post["id"] as your where variable I am assuming, so you could reduce this process significantly by doing a single query after formulating an array of post ids, something like this:
$postids = array();
foreach($posts as $post) {
$postids[] = $post['id'];
}
// Selecting from 1 table
$query = 'SELECT * FROM hashtags WHERE id IN ('. implode(",", $postids) .')';
This would fetch all the information on hashtags where the id is is one of your postids. That is just 1 table, you would likely want to fetch multiple, without knowing your database structure I'm going to be generic, so something like:
// Selecting and joining data from multiple tables
$query = ' SELECT author.name, table.col FROM posts
LEFT JOIN author ON author.id = post.author_id
LEFT JOIN table ON table.id = post.table_id
WHERE posts.id IN IN ('. implode(",", $postids) .')';
It is a bit more difficult to be more accuracy. I think joining tables would provide you a better result, you can even join counts for votes/comments. If that is not possible, you could query all data related to your posts and then formulate it in PHP, then you know exactly how many queries you have. For example, change your models to accept an array instead of a single post ID and then change your "WHERE post_id = x" to "WHERE post_id IN (x)" then you can do something like:
$postids = array();
foreach($posts as $post) {
$postids[] = $post['id'];
}
$hashtags = $this->HashTagsModel->get_hashtags($postids);
$author = $this->UserModel->get_user_details($postids);
$comment_count = $this->CommentModel->get_comments_count($postids);
$is_favourited = $this->FavouriteModel->is_favourited($postids);
$is_reposted = $this->RepostModel->is_reposted($postids);
$vote_status = $this->vote_status($postids);
$comments = $this->count_comments($postids);
This gets your queries outside of the loop, and you know there will only ever be 7 SQL queries, and not queries * posts. In PHP you would loop through the results of each array to assign each one back to posts based on its ID.
I have 2 tables, one is called post and one is called followers. Both tables have one row that is called userID. I want to show only posts from people that the person follows. I tried to use one MySQL query for that but it was not working at all.
Right now, I'm using a workaround like this:
$getFollowing = mysqli_query($db, "SELECT * FROM followers WHERE userID = '$myuserID'");
while($row = mysqli_fetch_object($getFollowing))
{
$FollowingArray[] = $row->followsID;
}
if (is_null($FollowingArray)) {
// not following someone
}
else {
$following = implode(',', $FollowingArray);
}
$getPosts = mysqli_query($db, "SELECT * FROM posts WHERE userID IN($following) ORDER BY postDate DESC");
As you might imagine im trying to make only one call to the database. So instead of making a call to receive $following as an array, I want to put it all in one query. Is that possible?
Use an SQL JOIN query to accomplish this.
Assuming $myuserID is an supposed to be an integer, we can escape it simply by casting it to an integer to avoid SQL-injection.
Try reading this wikipedia article and make sure you understand it. SQL-injections can be used to delete databases, for example, and a lot of other nasty stuff.
Something like this:
PHP code:
$escapedmyuserID = (int)$myuserID; // make sure we don't get any nasty SQL-injections
and then, the sql query:
SELECT *
FROM followers
LEFT JOIN posts ON followers.someColumn = posts.someColumn
WHERE followers.userID = '$escapedmyuserID'
ORDER BY posts.postDate DESC