I’m trying to create a separate table that would track read/unread posts. Using MySQLi I will have two tables items and items_tracking. When the page is rendered it will join the the tables and check if the user read the posts or not.
items
+-------+------------+----+
| id | created_by | .. |
+-------+------------+----+
| item1 | id12 | .. |
| item2 | id433 | .. |
+-------+------------+----+
items_tracking
+---------+---------+------+
| user_id | item_id | read |
+---------+---------+------+
| id1 | item1 | 0 |
| id2 | item2 | 0 |
| id94 | item1 | 1 |
+---------+---------+------+
Now the idea was that whenever a new item/post is created in the items table, it will also create rows in the items_tracking table for all users and with column read = 0. Problem is, I have no idea how to work around this since the foreign key I would use in items_tracking is still pretty much undetermined.
Any ideas on how to approach inserting in both tables at the same time, while the second table references the first?
You don’t need records with read=0 in the tracking table.
This query will work even if there is no corresponding record in
items_tracking; in this case, t.read in the result will beNULL. You only need to insert the records withread = 1, although you don’t need even this flag, you test fort.item_id IS NOT NULLto see if you have a record initems_tracking.