L
L
lolrofl012018-11-14 06:34:03
Laravel
lolrofl01, 2018-11-14 06:34:03

How to build a relationship so that it returns both parent and child information?

There is a table comments and users. Provided that comments->belongsTo(users) - only information about the user is displayed. Is it possible to build a link so that the result is a list of comments with users who left them? (Similar to join)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lieroes, 2018-11-14
@Lieroes

class User extends Authenticatable
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

class CommentController extends BaseController
{
    public function index()
    {
        return Comment::with('user')->get();
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question