Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.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 如何在Laravel中为hasOne()关系指定透视表_Php_Mysql_Laravel 4_Eloquent - Fatal编程技术网

Php 如何在Laravel中为hasOne()关系指定透视表

Php 如何在Laravel中为hasOne()关系指定透视表,php,mysql,laravel-4,eloquent,Php,Mysql,Laravel 4,Eloquent,我有两个模型,其中包括了透视表,以避免多态关系 role table id name description restriction table id rule status restriction_role table id restriction_id role_id 这种设置的原因是角色和限制实际上可以属于多个其他模型。在这种情况下,角色只能有1个限制。我通常会将其定义为 class Role extends Eloquent { public function restri

我有两个模型,其中包括了透视表,以避免多态关系

role table
id
name
description

restriction table
id
rule
status

restriction_role table
id
restriction_id
role_id
这种设置的原因是角色和限制实际上可以属于多个其他模型。在这种情况下,角色只能有1个限制。我通常会将其定义为

class Role extends Eloquent {
    public function restrictions()
    {
        return $this->hasOne('Restriction');
    }
}

这显然不起作用,因为Laravel不知道连接此关系的透视表。我可以通过使用多对多关系来轻松实现这一点,但这并不完全是我的模型的工作方式。在文档中没有看到任何关于定义此的内容。有什么想法吗?

正如@deczo在评论中所说的,belongtomany()是关于这里所有的工作。如果您只需要一个结果,但不能使用
hasOne()
关系,我建议使用
first()
方法返回第一个结果。

我通过使用
belongToMany
关系并为其定义自定义访问器来解决这个问题,如下所示:

public function foo()
{
    return $this->belongsToMany(App\Bar::class);
}

public function getFooAttribute()
{
    return $this->foo()->first();
}

为什么不能将
restriction\u id
添加到表
role
?另外,按照惯例,您的方法应该被称为
restriction()
(单数),因为它只返回一个restriction,可能使用hasManyThrough()或belongsToMany()关系a,尽管这只是一个入口,我想我可以给角色添加限制id,但角色不需要有restriction@MarkBaker我可以用belongtomany。这样行得通。但是,因为只有一个限制,所以我尝试使用hasOne()