与多对多关系的数据透视表创建一对多关系

时间:2015-11-02 12:37:57

标签: laravel eloquent

用户表结构:用户

id,name,username,password,created_at,updated_at

文章表格结构:文章

id,title,content,created_at,updated_at

关系表:article_user

id,article_id,user_id,is_active,created_at,updated_at

标签

id,name,user_id,created_at,updated_at

数据透视表article_user与标记的关系。 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');
    }
}

我想连接这些表,以便我可以像这样或类似的格式访问

$user->articles()->first()->tags;

并且应该能够像这样创建/更新

$user->articles()->first()->create(['title'=>'testing','content'=>'content'])->attach(['tag_id_1','tag_id_2','tag_id_3']);

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

试试这个:

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');
    }
}