R
R
root092018-11-12 16:19:40
Laravel
root09, 2018-11-12 16:19:40

What type of relationship is needed here?

There are tables:

Users (id, name)
Articles (id, title)
Favorites_list (id, user_id, article_id)
Article_rating_log (id, user_id, article_id, score)

UserModel:
public function favorite_list()
{
     return $this->hasMany('App\Models\FavoriteList');
}

Favorite List Model:
public function article()
{
     return $this->belongsTo('App\Models\Article');
}

public function user()
{
      return $this->belongsTo('App\Models\User');
}

There is a page where a list of the user's favorite articles is displayed ($user->favorite_list), how can I add the score field from the Article_rating_log table to this list , i.e. the rating that the user put on this article?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2018-11-12
@root09

Class FavoritesList()
{
    public function articleRatingLog()
    {   
        // Нужно указать несколько ключей для корректной связи
        // На обратной стороне также
         return $this->hasOne('App\ArticleRatingLog', ['user_id', 'article_id'], ['user_id', 'article_id']);
    }
}

Then get like this:
$user->favoriteList[$index]->articleRatingLog->score;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question