Getting related records using Pivot Table

23.04.2021 | 1068 | SQL

Preparing models and getting related records "through" the Pivot table. In the example, we get the related topics of the article by specifying its id.

In the example, the models are stored in the AppModels folder.
Table articles
id int(11)
name varchar(255)
Table themes
id int(11)
name varchar(255)
Table theme_article
id int(11)
article_id int(11)
theme_id int(11)
Model Article
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Article extends Model
{
public function themes()
{
return $this->belongsToMany('AppModelsTheme', 'theme_article', 'article_id', 'theme_id');
}
}
Model Theme
namespace AppModels;

use IlluminateDatabaseEloquentModel;
class Theme extends Model
{
public function articles()
{
return $this->belongsToMany('AppModelsArticle', 'theme_article', 'theme_id', 'article_id');
}
}
Getting the topics of the current article:
$themes = Article::find($articleIid)->themes()->get();
Adding multiple links to topics for an article:
$article->themes()->attach($themeId, ['theme_id' => $themeId]);



← Back

Comments (0)