Mam dwie tabele, posts
i likes
. Potrzebuję utworzyć zapytanie, przy użyciu Eloquent, które pobiera wszystkie posty, które zostały polubione przez konkretną user_id
.Zapytanie, gdzie kolumna znajduje się w innej tabeli
Innymi słowy, powinno być coś takiego:
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
tabela:
+----+---------+------------+-------------+
| 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
tabela:
+----+---------+---------+-------------+
| 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> |
+----+---------+---------+-------------+
Oto moja Post
klasa:
<?php
class Post extends Eloquent {
protected $table = 'posts';
public function likes()
{
return $this->hasMany('Like');
}
}
I klasa Like
:
<?php
class Like extends Eloquent {
protected $table = 'likes';
public function post()
{
return $this->belongsTo('Post');
}
}
Jak mogę to zrobić?
Dlaczego nie można po prostu użyć relacji laravel? Ustawić związek między użytkownikami lubiącymi? – rmobis