Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 按类别类型限制雄辩的多对多关系_Php_Mysql_Laravel_Eloquent_Relationship - Fatal编程技术网

Php 按类别类型限制雄辩的多对多关系

Php 按类别类型限制雄辩的多对多关系,php,mysql,laravel,eloquent,relationship,Php,Mysql,Laravel,Eloquent,Relationship,我正在尝试在Laravel中创建一个网站,在多对多关系中为多个实体使用单个类别表。我已经尝试过多态性,但它只能以一种方式工作,我需要能够查询以下内容: 所有服务类别的列表 所有文章类别的列表 服务/文章所属的所有类别的列表 类别中所有服务/物品的列表 这是下面的数据库结构。如您所见,categories中有一个type列,允许我选择service或article作为类别类型 我已经有了很好的工作原理,但我需要确保应用程序不允许类别类型意外混合。我的印象是,以下代码可以做到这一点: clas

我正在尝试在Laravel中创建一个网站,在多对多关系中为多个实体使用单个类别表。我已经尝试过多态性,但它只能以一种方式工作,我需要能够查询以下内容:

  • 所有服务类别的列表
  • 所有文章类别的列表
  • 服务/文章所属的所有类别的列表
  • 类别中所有服务/物品的列表
这是下面的数据库结构。如您所见,categories中有一个type列,允许我选择service或article作为类别类型

我已经有了很好的工作原理,但我需要确保应用程序不允许类别类型意外混合。我的印象是,以下代码可以做到这一点:

class Category extends Model
{
    public function services()
    {
        return $this->belongsToMany('App\Service')->where('type', '=', 'service')->withTimestamps();
    }
    public function articles()
    {
        return $this->belongsToMany('App\Article')->where('type', '=', 'article')->withTimestamps();
    }         
}
class Service extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Category')->where('type', '=', 'service')->withTimestamps();
    }
}
class Article extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Category')->where('type', '=', 'article')->withTimestamps();
    }
}
正如我在文档中所读到的,在
之后添加
where
将限制它。没有

我插入以下数据:

id  name            type    created_at          updated_at
1   Category One    service 2016-01-31 13:23:29 2016-01-31 13:23:29
2   Category Two    article 2016-01-31 13:24:02 2016-01-31 13:24:02

id  name        created_at          updated_at
1   Service One 2016-01-31 13:23:10 2016-01-31 13:23:10
然后运行此查询:

$category = App\Category::find(2);
$category->services()->attach(1);
尽管它将服务附加到类型为“article”的类别中,但它仍然可以完美地工作。它不应该插入此数据


如何使限制正常工作?

我将使用应用于关系的范围。提供了比way@MikeMiller在这种情况下,它是如何工作的?我正在打电话,但看起来您应该创建一个公共模型类来继承。在这里面放了两个作用域函数(检查文档,不是很难),因为它们似乎是一些模型的共同点。这些文档还显示了如何将范围应用于关系。如果这看起来像是工作后,一些工作代码,我会做我的帮助out@MikeMiller如果类别类型设置为
服务
,是否允许我阻止插入文章成功?基本上,这就是我想要的,一种内置于模型中的固有限制,以防止类别类型被混合。这就是我所需要的,真的。