0

I have several tables in my database. Blogs, Users, Posts, Tags are the main ones. Also I have linking tables: User_blogs, Blog_posts & Post_tags.

My question is how to use Laravel's classes and methods like belogs_to(), has_many(). I need someone shed light on it. I've read many articles and documentation, but I'm still confused.

1 Answer 1

1

Generally laravel is smart enough to detect many-to-many relationships if you set up your tables properly Both table names should be not pluralized in the intermediate/pivot table so you should have Users, Blogs, Posts, Tags as your individual tables and User_Blog, Blog_Post, Post_Tag as your intermediate tables. In those tables the cols should properly reflect the tablename_id (in lowercase) so in User_Blog it should have 3 cols id, user_id, blog_id etc and so on for the other columns.

In your models you just need to set up the many-to-many relationships

class User extends Eloquent
{
     public function blogs()
     {
         return $this->has_many_and_belongs_to('Blog');
     }
}

And so on for each model. If changing the structure isn't an option then simply add the table name in the many-to-many relationship like so return $this->has_many_and_belongs_to('Blog', 'User_blogs');

Sign up to request clarification or add additional context in comments.

3 Comments

I'd just like to add in that you will thank yourself later if you go ahead and adopt the standard Laravel ORM table naming convention now. ie: blogs, users, blog_user
I do not know why but it's asking me for columns: user_blogs.created_at & user_blogs.updated_at. Are those necessary?
They are expected. Just put public static $timestamps = false; in your model to disable Laravel's built in timestamps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.