D
D
Dmitry Kuznetsov2017-09-11 09:30:57
Laravel
Dmitry Kuznetsov, 2017-09-11 09:30:57

How to get comments to the news and at the same time the author of the comment?

How to get comments to the news and at the same time the author of the comment?

news database
83f9836a8ef84e9c9d49a409fdc9d68e.png
Comments DB
55bf5995f55f40d29ea2f3b35971c966.png
User database
4200d7ad2b6f4a588513f2288aee48d2.png

I receive all comments related to the news:
/* Получение одной новости */
    public static function getIDNews($newsID){
        $getIDNews = News::with(['comments', 'authorComments'])
                            ->where('id_news', '=', $newsID)
                            ->first();

        return $getIDNews;
    }

/* Получение авторов комментариев */
    public function authorComments(){
        return $this->belongsTo(User::class,  'author_comments', 'id_users');
    }

    /* Получение всех комментариев к новости */
    public function comments(){
        return $this->hasMany(Comments::class, 'news_comments', 'id_news');
    }

But "authorComments" gives me null. What am I doing wrong, thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kuznetsov, 2017-09-11
@dima9595

I decided not to worry too much and wrote the following code:

/* Получение комментариев и их авторов */
    public static function getCommentsIDNews($newsID){
        $getCommentsIDNews = Comments::where([
                            ['news_comments', '=', $newsID],
                            ['status_comments', '=', 1]
                        ])
                        ->join('users', 'author_comments', '=', 'id_users')
                        ->get();

        return $getCommentsIDNews;
    }

M
Maxim Fedorov, 2017-09-11
@Maksclub

I'm not from the Laravel world, but I see a reference to the User model, in this model, most likely, the field is not id_users, but id
krch. show the `users` table again
, maybe there is no such user in the `users` table at all

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question