Ich brauchen 1 Post erhält nach Anforderungs-ID mit folgenden Struktur:verschachtelte Abfragen in Laravel Query Builder
postID;
postTitle;
postContent;
postImage;
bandName;
genreName;
Tags: [tagId, tagName];
Kommentare: [commentId, commentBody, commentCreatedAt].
Tische Struktur:
Beiträge (id, Titel, Inhalt, Bild, band_id, Zeitstempel);
Tags (ID, Name);
post_tag (post_id, tag_id);
Kommentare (id, body, post_id, user_id, Zeitstempel).
ich verschiedene Variationen von Abfrage, so wie versucht haben:
$post = DB::table('posts as p')
->select('p.id as postId',
'p.title as postTitle',
'p.content as postContent',
'p.image as postImage',
'b.name as bandName',
'g.name as genreName',
DB::raw("(SELECT t.id as tagId, t.name as tagName
FROM tags as t
JOIN post_tag as pt ON t.id = pt.tag_id
WHERE pt.post_id = $request->postId
GROUP BY tagId) as tags"))
->join('bands as b', 'b.id', 'p.band_id')
->join('genres as g', 'g.id', 'b.genre_id')
->where('p.id', $request->postId)
->groupBy(
'postId',
'postTitle',
'postContent',
'postImage',
'bandName',
'genreName')
->get();
Aber ich blieb stecken Tags holen ((es mir Fehler zurückgibt: SQLSTATE [21000]: Cardinality Verletzung: 1241 Operanden- sollte enthalten 1 Spalte (n) oder andere.
Wie Tags für den Posten zu bekommen (die Abfrage für Kommentare wird ähnlich sein)? nicht so verschachtelte Abfragen verarbeiten kann (( schätzen ich Hilfe.
Aktualisierung 1.
Versuchte:
$post = DB::table('posts as p')
->select('p.id as postId',
'p.title as postTitle',
'p.content as postContent',
'p.image as postImage',
'b.name as bandName',
'g.name as genreName',
't.id as tagId',
't.name as tagName')
->join('post_tag as pt', 'p.id', 'pt.post_id')
->join('tags as t', 't.id', 'pt.tag_id')
->join('bands as b', 'b.id', 'p.band_id')
->join('genres as g', 'g.id', 'b.genre_id')
->where('p.id', $request->postId)
->groupBy(
'postId',
'postTitle',
'postContent',
'postImage',
'bandName',
'genreName',
'tagId')
->get();
Ergebnis:
[{
"postId",
"postTitle",
"postContent",
"postImage",
"bandName",
"genreName",
"tagId",
"tagName"
},{
"postId",
"postTitle",
"postContent",
"postImage",
"bandName",
"genreName",
"tagId",
"tagName"
}]
So "postID", "postTitle", "postContent", "postImage", "Bandname", "genreName" sind dupliziert (()
aktualisiert meinen Code. Irgendwie muss ich ein Array von Tags bekommen ... –
Sie müssen eine foreach-Schleife verwenden, um das Ergebnis nach Ihren Bedürfnissen zu strukturieren, – YouneL