0

I did relationships between different models all the time but for some reason I can't get this one to work. I tried everything I can find on Google but no luck.

I want to create a relation between Comment and User models. Any user can make many comments and I need to use email address of the commenter.

Basically, this:

$comments->user->email

My database looks like this:

userdata
--- id
--- username
--- email

comments
--- id
--- username
--- comment

userdata.username and comments.username should be related to eachother.

I pass the data to views like this:

Comment::with('user')->where('on', $news->id)->orderBy('id', 'DESC')->take(10)->get()

No matter what I try, I can't get it to work. Relations are not created. Maybe I came across a strange laravel bug?

Those are my models: (I write the default ones since I messed them up so much trying different approaches)

class Comment extends Eloquent {

    public static $key = 'id';
    protected $table = 'comments';
    public $timestamps = true;
}


class User extends Eloquent implements UserInterface, RemindableInterface {
    protected $table = 'userdata';
    public $timestamps = false;

    //It contains necessary imports and methods, I cutted them off for stackoverflow
}

Does anybody have an idea how can I solve this?

2 Answers 2

1

In a normal database scheme, docs written here. In your case, this should work:

// Model: Comment
public function user()
{
    //belongsTo('User', 'local_key', 'parent_key'); so:
    return $this->belongsTo('User', 'username', 'username');
}

//Then get this
Route::get('/test', function()
{
    return Comment::find($id)->user->email;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Strange enough, it didn't work but I dropped username column on my comments table and replaced it with user_id. That way, it worked. I'll pick your answer as selected regardless.
I'm glad to help you. You can edit my post if you think other users will benefit from this.
0

This code $comments->user->email is not going to work.

$comments is an array of comments. It does not hold any shared reference to a user, you will have to pull a particular comment out and read the associated user.

Have you added the belongsTo() method to your comment model?

1 Comment

Well, $comments is an array. I didn't want to include my foreach loop. Normally it is $comments[$k]->user->email, or $v->user->email

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.