Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Many-to-many relations

Hi! I have 3 tables (models) News Tags NewsTags

When Im making many-to-many relations, I can easily get tags from news item. But how can I get news from tag item?

news

<?php
$this->hasManyToMany(
            "id",
            "NewsToTags",
            "news_id", "tag_id",
            "Tags",
            "id",
            array('alias' => 'NewsToTags')
        );

tags

<?php
$this->hasManyToMany(
            "id",
            "NewsToTags",
            "tag_id", "news_id",
            "News",
            "id",
            array('alias' => 'news')
        );

newstotags

<?php
$this->belongsTo("news_id", "News", "id", array('alias' => 'news'));
        $this->belongsTo("tag_id", "Tags", "id", array('alias' => 'tags'));

Im getting very nicely the tags from news item

<?php
foreach ($news->NewsToTags as $NewsTag) {
            $tags[$NewsTag->id] = $NewsTag->name;
        }

But I cant get in same way news from tag item.

Question:

  1. Is im doing right (the docs are a bit not much clear for me)

  2. How to get news from tag item (the best way)?

  3. Can I get not all columns but only for example id and name in the code above?



32.7k
Accepted
answer
edited Sep '15

Your code looks ok. Try this 3 things:

  1. Rename the alias from "NewsToTags" to "tags"

  2. Write the full namespace of the model. Eg:

$this->hasManyToMany(
            "id",
            "Your\Name\Space\NewsToTags",
            "news_id", "tag_id",
            "Your\Name\Space\Tags",
            "id",
            array('alias' => 'tags')
        );
  1. Try with this code:
// Get tags for news:
foreach ($newsObject->tags as $tag) {
    echo $tag->name; // where "name" is yourColumnName from DB table "tags"
}

// Get news for tag
foreach ($tagObject->news as $news) {
    echo $news->title;
}

Why you cant ? Just do $tag->getNews()(if you have getter)/$tag->news