JackyVip's avatar

Define eloquent relationships for tables

How can a define a relationships for these tables:

comments: (table fields) id, commentable_id, commentable_type, type
comment_messages: id, message, comment_id
comment_posts: id, comment_id, message_id, user_id, name, created_at, update_at
comment_rating: id, rating, message_id, comment_id 

for comments i have set Polymorphic relationship.

0 likes
6 replies
bobbybouwmann's avatar

Well, comment is just a model here. So basically it works the same as all the other relationships

class Comment extends Model
{
    public function commentMessages():
    {
        return $this->hasMany(CommentMessage::class);
    }

    public function posts():
    {
        return $this->hasMany(CommentPost::class);
    }


    public function ratings():
    {
        return $this->hasMany(CommentRating::class);
    }
}

class CommentMessage extends Model
{
    public function comment()
    {
        $this->belongsTo(Comment::class);
    }
}

class CommentPost extends Model
{
    public function comment()
    {
        $this->belongsTo(Comment::class);
    }
}

class CommentRating extends Model
{
    public function comment()
    {
        $this->belongsTo(Comment::class);
    }
}

Documentation: https://laravel.com/docs/6.x/eloquent-relationships#one-to-many

JackyVip's avatar

Ok, and how should i create or update a new comment, commentMessage, commentPost, commentRating?

I have something like this:

$comment = $product->comments;

if(!$comment) {
$comment = new Comment;
$comment->commentable_id = $product->id;
$comment->commentable_type = Product::class;
$comment->type = 'Review'
$comment->save();
}

$new_c_message = $comment->commentMessage()->create([
    'message' => $request->message;
]);

$comment->commentPost()->create([
    'message_id' => $new_c_message->id,
    'user_id' => Auth::id(),
    'name' => $request->name,
]);

$comment->commentRating()->create([
    'rating' => $request->rating,
    'message_id' => $new_c_message->id,
]);
jlrdw's avatar

A good start would be to work some of the examples in the documentation. Just set up a practice project just to work examples.

JackyVip's avatar

The problem is 'message_id' is not filled in the database.

bobbybouwmann's avatar
Level 88

@jackyvip You need to make sure all columns are fillable when saving

class CommentPost extends Model
{
    protected $fillable = ['message_id', 'user_id', 'name'];
}

Please or to participate in this conversation.