ytre
2 months ago

Eloquent relationships - Get all post with category name of auth user

Posted 2 months ago by ytre

Hey, I have this base structure:

posts:
id
title
content
category_id
created_at
updated_at

categories:
id
name

post_user: (pivot)
post_id
user_id

users:
(standard fields)

One post can have many authors, only one category can be assigned to a post, one user can have many posts.

How do you download with Eloquent all auth user posts with a category name?

In phpmyadmin I created a mysql query that returns the data I need:

SELECT p.title,c.name FROM posts p JOIN categories c ON c.id=p.category_id JOIN post_user pu ON pu.post_id=p.id WHERE pu.user_id=$id

// $id = auth user id

PS sorry for my bad english

Please sign in or create an account to participate in this conversation.