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" }]},
]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…