Support the ongoing development of Laravel.io →
Database Eloquent Blade
Last updated 4 months ago.
0

relationships still stump me sometimes, but if I am correct, you should call

$forum->lastcomment()->id

//instead of
$forum->lastcomment->id
0

Your understanding on foreign key and local key are wrong. Your relations are incorrect as well.

So, here's the setup I assume:

Tables:
forums: id, last_comment_id, ...
topics: id, ...
comments: id, topic_id, ...

then id are always local keys in the context of any relation. That said, here are your relations:

// Forum
public function lastcomment()
{
  return $this->belongsTo('Comment', 'last_comment_id');
}

// Comment
public function forum()
{
  return $this->hasOne('Forum', 'last_comment_id');
}

However having this setup your Forum depends on the comments, which is not the way to go. Instead create proper relations:

// Forum
public function comments()
{
  return $this->hasManyThrough('Comment', 'Topic');
}

no relation from Comment to the Forum, since you will call $comment->topic->forum if you need.

Also, for the latest comment for given forum, use this: http://softonsofa.com/tweaking-eloquent-relations-how-to-get-l...

and you will be able to do what you wanted:

if (count($forum->lastcomment)) {  // chech if there's any comment first
  $forum->lastcomment->id
}
Last updated 7 years ago.
0

Sign in to participate in this thread!

Full Stack Europe

Your banner here too?

Maxime-BHA maxime-bha Joined 25 Jun 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 Laravel.io - All rights reserved.