Users table structure: users
id, name, username, password, created_at, updated_at
Article table structure: article
id, title, content, created_at, updated_at
Relationship table: article_user
id, article_id, user_id, is_active, created_at, updated_at
Tags
id, name, user_id, created_at, updated_at
Relation of pivot table article_user with tags. table: article_user_tag
tag_id, article_user_id
class User extends Model
{
protected $fillable = ['name','username','password'];
public function articles()
{
return $this->belongsToMany('App\Article')->withPivot('is_active')->withTimestamps();
}
public function tags()
{
return $this->hasMany('App\Tag');
}
}
class Article extends Model
{
protected $fillable = ['title','content'];
public function users()
{
return $this->belongsToMany('App\User')->withPivot('is_active')->withTimestamps();;
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
class Tag extends Model
{
protected $fillable = ['title','content'];
public function articles()
{
return $this->belongsToMany('App\Article');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
I want to connect these table so I can access like this or similar format
$user->articles()->first()->tags;
and should be able to create/update as well, smth like this
$user->articles()->first()->create(['title'=>'testing','content'=>'content'])->attach(['tag_id_1','tag_id_2','tag_id_3']);
Any help is much appreciated
Try this:
class User extends Model
{
protected $fillable = ['name','username','password'];
public function articles()
{
return $this->hasMany('App\ArticleUser')->with('article');
}
public function tags()
{
return $this->hasMany('App\Tag');
}
}
class ArticleUser extends Model
{
public funciton article()
{
return $this->belongsTo('App\Article');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
class Article extends Model
{
protected $fillable = ['title','content'];
}
class Tag extends Model
{
protected $fillable = ['title','content'];
public function articles()
{
return $this->belongsToMany('App\ArticleUser')->with('article');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments