How can I reference the data in the messages_threads (Thread model) table while inside the whereHas clause?
Jun 4, 2015
9
Level 11
whereHas constraints not being followed
Here are my tables with sample data
mysql> select * from messages_threads;
+----+--------------------------------+---------+------------+---------------------+---------------------+
| id | subject | creator | deleted_at | created_at | updated_at |
+----+--------------------------------+---------+------------+---------------------+---------------------+
| 2 | piI4yBpwhBlo31YGBEQC59FbbkUm8u | 3 | NULL | 2015-06-05 00:06:38 | 2015-06-05 00:06:38 |
+----+--------------------------------+---------+------------+---------------------+---------------------+
1 row in set (0.00 sec)
mysql> select * from messages_participants;
+----+-----------+---------+---------------------+---------+---------------------+---------------------+
| id | thread_id | user_id | last_read | deleted | created_at | updated_at |
+----+-----------+---------+---------------------+---------+---------------------+---------------------+
| 1 | 2 | 3 | 2015-06-05 00:06:48 | 0 | 2015-06-05 00:06:38 | 2015-06-05 00:06:38 |
| 2 | 2 | 1 | 0000-00-00 00:00:00 | 0 | 2015-06-05 00:06:38 | 2015-06-05 00:06:38 |
| 3 | 2 | 2 | 0000-00-00 00:00:00 | 0 | 2015-06-05 00:06:38 | 2015-06-05 00:06:38 |
+----+-----------+---------+---------------------+---------+---------------------+---------------------+
3 rows in set (0.00 sec)
Here is my eloquent query
$threads = Thread::whereHas('participants', function($q)
{
$q->where('messages_participants.user_id', 3)
->where('messages_participants.last_read', '<', 'messages_threads.updated_at');
})->get();
The issue is that the thread (only one in DB) is being returned to user 3 and it should not be. Only users 1 and 2 should be getting Thread 2 returned.
Here is the query eloquent has built
select * from `messages_threads` where `messages_threads`.`deleted_at` is null and (select count(*) from `messages_participants` where `messages_participants`.`thread_id` = `messages_threads`.`id` and `messages_participants`.`user_id` = '3' and `messages_participants`.`last_read` < 'messages_threads.updated_at') >= 1
Could the issue be that I am trying to reference messages_threads.updated_at while inside the whereHas and it is the parent function data? If so, how would I go about referencing it and making this query work?
Thread model table `messages_threads`
-> hasMany('Participant')
Participant model table `messages_participants`
-> belongsTo('Thread')
Please or to participate in this conversation.