Answer the question
In order to leave comments, you need to log in
How to display all posts by tag through relationships?
Good day
, I started to study Laravel, I can’t understand and deal with polymorphic relationships.
It turned out that I have 3 tables:
1) articles
2) categories:
3) categoryable
actually the 3rd intermediate table contains: category_id (category id) and categoryable_id (post id) )
Posts can have several categories, and I can't figure out how to output, for example, if I do something like "My feed" where I subscribe to several categories
, how is such a page formed?
Or rather, what would the output look like?
Answer the question
In order to leave comments, you need to log in
Polymorphic links are needed when one model can be related to several other models. For example: the "tag" model can be associated with both the "article" model and the "video" model .
And you have the usual many-to-many relationship: one post can have several categories at once, and one category can contain several posts at once.
We go to the Laravel documentation ( https://laravel.com/docs/master/eloquent-relations... and do everything as described there:
// Article.php
class Article extends Model
{
// ...
public function categories()
{
return $this->belongsToMany('App\Category');
}
// ...
}
// Category.php
class Category extends Model
{
// ...
public function articles()
{
return $this->belongsToMany('App\Article');
}
// ...
}
articles
- id
- title
- desc
categories
- id
- slug
- name
article_category
- id
- article_id
- category_id
$subscribedOn = [ 1, 2, 3 ]; // ID категорий, на которые подписан пользователь
$articlesForUser = Article::whereHas('categories', function(Builder $query) use ($subscribedOn) {
$query->whereIn( 'categories.id', $subscribedOn );
})->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question