I have two tables, posts and likes . I need to create a request using Eloquent, which receives all the messages that a particular user_id liked.
In other words, it should be something like this:
SELECT * FROM posts p LEFT JOIN likes l ON p.id = l.post_id WHERE l.user_id = 2 ORDER BY l.created_at DESC
posts table:
+----+---------+------------+-------------+ | id | user_id | message | created_at | +----+---------+------------+-------------+ | 1 | 2 | Hello! | <SOME TIME> | | 2 | 3 | World! | <SOME TIME> | | 3 | 2 | Something. | <SOME TIME> | | 4 | 2 | Another. | <SOME TIME> | +----+---------+------------+-------------+
likes table:
+----+---------+---------+-------------+ | id | post_id | user_id | created_at | +----+---------+---------+-------------+ | 1 | 1 | 2 | <SOME TIME> | | 2 | 2 | 2 | <SOME TIME> | | 3 | 1 | 3 | <SOME TIME> | | 4 | 3 | 2 | <SOME TIME> | +----+---------+---------+-------------+
Here is my Post class:
<?php class Post extends Eloquent { protected $table = 'posts'; public function likes() { return $this->hasMany('Like'); } }
And the Like class:
<?php class Like extends Eloquent { protected $table = 'likes'; public function post() { return $this->belongsTo('Post'); } }
How can i do this?
source share