E
E
Erl2019-08-19 17:23:54
Laravel
Erl, 2019-08-19 17:23:54

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

1 answer(s)
R
Razgelday, 2019-08-20
@NooBiToo

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');
    }

    // ...

}

Then the tables in the database should be like this:
articles
 - id
 - title
 - desc

categories
 - id
 - slug
 - name

article_category
 - id
 - article_id
 - category_id

Now, let's say you have a list of id's of the categories the user is subscribed to (the $subscribedOn variable ). Then, you can get all the posts for this user's feed like this:
$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 question

Ask a Question

731 491 924 answers to any question