display multiple categories codeigniter - php

I have a relational database in this format
Table: posts
Columns: post_id,post_title,post_content
Table: categories
Columns: category_id,category_name
Table: posts_categories
Columns: post_id,category_id
Posts can have multiple categories so i store them in posts_categories using post and category id, when i get results from database using below query, it just display the last category, Is it possible to display all categories otherwise i have to run a separate query, here my code.
$this->db->select("p.*,pc.*,c.*");
$this->db->where('post_id', $id);
$this->db->from('posts AS p');
$this->db->join('posts_categories AS pc', 'pc.post_id = p.post_id', 'inner');
$this->db->join('categories AS c', 'pc.category_id = c.category_id', 'inner');
$q = $this->db->get();
Thanks for any help.

You didn't mention what fields you actually select. However, you can SELECT p.title, c.category_name and after doing your query (mentioned in the question), you should have multiple rows in your result, containing the posts title and a category name for that post.
Now if you want you can group these categories by posts in php, building a new array from the db result.

Related

laravel get data when give id not match with join table id

here is my category table data
id
1
2
6
7
when in my post bale I join with this category table
here is my post table sample data
ID = 1,
name = 'hellow'
category id = 4 (i join with category table but selected category is
deleted)
here is my index SQL query (when categy_id match with the category.id) then only its fetch
$post = DB::table('posts)->join('category','posts.category_id','categories.id')-.paginate(10);
for some reason, the selected category can be deleted so I try to get category deleted post data
here is my query
$cpost = DB::table('posts')->join('categories','posts.category_id', '!=' ,'categories.id')->select('post.*')->paginate(5);
but above query duplicate post data based on available category data
i want all post data which are category id is not matched with in category table id how can i get that ?
Try this. Key is the leftJoin instead of default innerJoin (join).
// posts without assigned or existing category
$posts = \DB::table('posts')
->leftJoin('category','posts.category_id','categories.id')
->whereNull('categories.id')
->paginate(10);
why are you doing a join for this? you already have category id stored in your post table.
$cpost = DB::table('posts')->where('category_id','!=', $category_id)->paginate(5);
Just try it:
$cpost = DB::table('posts')
->join('categories','posts.category_id', '=' ,'categories.id')
->select('post.*', 'categories.*')
->whereNotIn('posts.category_id', DB::raw('select id from categories'))
->paginate(5);

How to use Multi table queries in Laravel without using Eloquent Relationships

I am using Laravel to create API for my app, later it will be integrated with react front-end. I have two tables, Post & Comment. Post table contains info about posts & comment table contains the comments data about each post. Below is there structure,
Post Table
post_id (Primary Key)
post_title
post_description
Comment Table
comment_id (Primary Key)
comment_text
post_id (Foreign Key)
I need to take post_id, post_title from post table and total no of comments on each post from comment table & want the json data to be showed like this
{
"post_id": 1,
"post_title": "some title",
"total comments": "4"
},
I know how to write sql queries for these but just having issue with showing the data like the above. Below is the code which I am using.
$allPostQuery= DB::select('select * from post');
foreach($allPostQuery as $allPostQuery)
{
$postId= $allPostQuery->post_id;
$totalCommentsQuery= DB::select('select count(comment_id) as totalComments from comment where post_id=:postId',["postId" => $postId ]);
}
return \Response::json([$allPostQuery,$totalCommentsQuery]);
But thats not working. I am confused about the looping of post ids to get total comments for each post. Do I have to do this in front-end using react foreach loop? Anyone can suggest any help. Thanks
As per your question you just need the Post ID, TITLE and Count of the Comments of each posts:
$query = DB::select('
SELECT
p.post_id,
p.title,
c.total AS totla_comments
FROM posts p
INNER JOIN
(
SELECT post_id, COUNT(post_id) AS total FROM comments WHERE comments.post_id = post_id
GROUP BY post_id
) c
ON p.post_id = c.post_id
');
echo json_encode($query);
Use json_encode (Laravel has ->json() function) if you want the data return should be in JSON format.
Looking at your approach:
First you query the post
You loop the post again and query the comments
This will impact your performance speed and should be avoided.

MySQL Stored functions and php

So i have this query to fetch all posts
select id, title
from posts
where type = 'article'
and i have a stored function that calculate the total of views and return the result
i know i can execute it like
select totalView(id)
but how can i merge the two queries to return all posts with the total view of each post
maybe something like
select id, title, totalView(id) as total
from posts
where type = 'article'
Thank you.
select count(*) as total, id, title from posts where type = 'article'
EDIT : It will count all the rows of $id
select count(*) as total, id, title from posts where type = 'article' AND id = $id;

Where query from other table + Doctrine

I'm stuck with creating a where query. I have table item with item_id, item_title, item_description, item_created, item_approved. I also have a table article with PK item_id (from item table) and article_body. The last table is media with medium_id, item_id (FK), medium_url and medium_type.
Now I would like to select all the data from media where item.item_approved is not NULL and where item.item_id ins't present in the article table.
Now I can select all the data from media where item.item_approved is not NULL. But now I need to do another check that he doesn't select the items that are also in article table. My query so far:
$repository = $entityManager->getRepository('VolleyScoutBundle:Media');
$query = $repository->createQueryBuilder('m')
->join('m.item', 'i')
->where('i.itemApproved is not NULL')
->getQuery();
Most likely that you must use 2 queries. With JOINs it can not be done.

Displaying alternate column when using foreign keys

I have an issue regarding PHP, MySql and foreign keys. I understand foreign keys and have a relationship between two tables in place as described:
Let's say I have 2 tables: 'vehicles' and 'manufacturers'.
Each row in the 'vehicles' table includes a manufacturerId column which is a foreign key relating to the 'manufacturers' table. This is set up nicely, in PhpMyAdmin when I insert a new row into the 'vehicles' table the manufacturerId column has a drop-down menu with the manufacturerId's listed as options. Very nice.
BUT: In my application, of course, I don't want the user to have to know (or have to guess) what the correct number for 'Ford' or 'BMW' is when they add a new vehicle, I want them to be able to choose the manufacturer by name.
But how does the application know the manufacturer names based on the manufacturerId? How does the application know there is a relationship between the 2 tables? Am I supposed to hard-code the relationship in the application? Am I supposed to modify all my queries to have a JOIN between the 2 tables? Or hard-code a query to get a list of manufacturers every time I want to display a drop-down of manufacturers?
Is there a way for the application to know about relationships between tables and be able to display data from a text column instead of the int column used as the ID?
Assuming your 2 table are structured like this:
VEHICLES
id
manufacturerId
vehicleName
MANUFACTURERS
id
manufacturerName
You would create your vehicle manufacturer select menu for users by querying the database like this:
// query the database
$q = 'SELECT id, manufacturerName FROM manufacturers';
$r = mysqli_query($link, $q);
// display a select menu using id and manufacturerName
echo '<select name="manufacturer">';
while($row = mysqli_fetch_assoc($r)) {
echo '<option value="'.$row['id'].'">'.$row['manufacturerName'].'</option>';
}
echo '</select>';
To use the post data from that menu to add a vehicle & manufacturer id to your vehicles table:
$q = "INSERT INTO vehicles (manufacturerId, vehicleName) VALUES ({$_POST['manufacturer']}, '{$_POST['vehicleName']}')";
mysqli_query($link, $q);
Finally, if you wish to select the vehicle name and manufacturer in the same query, you would join the tables like this:
// Select vehicle name and manufacturer for vehicle with id of 1
$q = "SELECT v.vehicleName, m.manufacturerName, v.id AS vehicleId, m.id AS manufacturerId
FROM vehicles AS v, manufacturers AS m
WHERE v.manufacturerID = m.id
AND v.id = 1";
mysqli_query($link, $q);
I think that should answer all your questions in one way or another!

Categories