Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

php - Display parent id with many-to-many relationship

I have a relationship many-to-many. I need to fetch all tags with parent id. For example it can look like this:

[
   { article_id: 1, id: 1, name: "tag 1" },
   { article_id: 1, id, 2, name: "tag 2" },
   { article_id: 2, id: 1, name: "tag 1" }
]

Look that tag 1 is two times for two articles. Propably I can make loop inside loop but it doesn't look proffesional. Could you show me the best solution of this problem?

@Edit: I created this code:

public function articles(){
    $article = [];
    $allArticles = Articles::all();
    foreach($allArticles as $key => $a){
        $obj = new stdClass();
        foreach($a->tags as $t){
            $obj->article_id = $a->id;
            $obj->name = $t->name;
            array_push($article, $obj);
        }

    }


    return json_encode($article);
}

But it doesn't work like I want. It display only one tag for one article, not all. Any idea?

question from:https://stackoverflow.com/questions/65860731/display-parent-id-with-many-to-many-relationship

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't quite understand what you are trying to achieve via the code snippet you have provided. However, as per the opening line of your question if you want to retrieve all tags with associated articles' ids then you can try the below

$tags = Tag::with('articles')
    ->get()
    ->map(function($tag) {
        $tag->articleIds = $tag->articles->pluck('id');
        unset($tag->articles);
        return $tag;
    });

This will give you an output like

[
   { id: 1, name: "tag 1", articleIds: [1,2] },
   { id, 2, name: "tag 2", articleIds: [1] },
]

If you want it other way around i.e. get the article with associated tags

$articles = Article::with('tags:id,name')
    ->get()
    ->map(function($article) {
        $object = new StdClass;
        $object->article_id = $article->id;
        $object->tags = $article->tags;
        return $object;
    });

Which will give you an output like

[
   { article_id: 1, tags: [{id: 1, name: "tag 1" }, {id, 2, name: "tag 2"}] },
   { article_id: 2, tags: [{id: 1, name: "tag 1" }]},
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...