多态多对多关系 [英] Polymorphic many-to-many relation

查看:195
本文介绍了多态多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ photo =照片::寻找(1); 
$ photo-> articles() - > attach(2);

像这样的东西不行,给出


错误:调用未定义的方法
Illuminate\Database\Query\Builder :: articles()'


如何做到正确的方式?



模型

  class Tag扩展Eloquent 
{
public function articles()
{
return $ this-> morphedByMany('Article','taggable') ;
}

public function photos()
{
return $ this-> morphedByMany('Photo','taggable');
}
}
class Article Eloquent
{
public function tags()
{
return $ this-> morphToMany(' Tag','taggable');
}
}

类照片扩展Eloquent
{
public function tags()
{
return $ this-> ; morphToMany('Tag','taggable');
}
}


解决方案

得到它的工作...基本上它是多态+多对多关系结合。我以为它不需要标签表。标签表用作枢轴表,标签是包含基于数据透视表(taggables表)连接模型的标签对象的表


I couldn't get related models in many-to-many polymorphic relation saved into database.

$photo = Photo::find(1);
$photo->articles()->attach(2);

something like this wouldn't work and gives

error: Call to undefined method Illuminate\Database\Query\Builder::articles()'

How to do it the right way?

Models

class Tag extends Eloquent
{
    public function articles()
    {
        return $this->morphedByMany('Article', 'taggable');
    }

    public function photos()
    {
        return $this->morphedByMany('Photo', 'taggable');
    }
}
class Article extends Eloquent
{
    public function tags()
    {
        return $this->morphToMany('Tag', 'taggable');
    }
}

class Photo extends Eloquent
{
    public function tags()
    {
        return $this->morphToMany('Tag', 'taggable');
    }
}

解决方案

Finally got it working... Basically it's polymorphism + many to many relationship combined. I thought it don't require tags table. Taggables table acts as pivot table and tags is the table which contains Tag objects that connect models based on pivot table (taggables table)

这篇关于多态多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆