PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 16, 2022

[FIXED] Laravel Eloquent hasMany relationship

 February 16, 2022     eloquent, laravel, php     No comments   

Issue

Hi I am new to Laravel and currently in am using Laravel 4.2. I am trying to create an application where I have users, posts and comments table and have the following model

User Model

function posts() {

    return $this->hasMany('Post');
}


function comments(){

    return $this->hasMany('Comment');
}

Post Model

function users() {

    return $this->belongsTo('User');
}

function comments() {

    return $this->hasMany('Comment');
}

Comment Model

function posts(){

    return $this->belongsTo('Post');
}

function users(){

    return $this->belongsTo('User');
}

What I want to achieve :

user's Post and comment for Post

eg:: User1 -> Post one -> comment for post one

What I have done So far:::

$user = User::find(1);
$post = $user->posts()->get();

I am able to get post but how do i get comment for specific post??

Update

Thanks to @Bogdan for his help I am able to get post and comment for user. But as usual had another problem.

What I got:

 foreach($user->post AS $post) {

 foreach ($post->comment AS $comment ) {

 $comment->commentcontent; $user->uername;
}
}//first foreach

This is what I get

comment one by user1.
comment two by user1.

But in reality comment one is created by user1 and comment two is created by user2.

Thank you for your help in advance. Can post full code if needed.


Solution

You want to get user that made the comment, so get that user from the comment object.

Try this

$user = User::find(1);
$posts = $user->posts;

foreach ($posts as $post) {
    foreach ($post->comments as $comment) {
        echo $comment->commentcontent;
        echo $comment->users;
    }
}


Answered By - wiseodd
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing