Chr*_*ris 1 php mysql eloquent laravel-4
我有几个模型,我已经包括数据透视表,以避免多态关系.
role table
id
name
description
restriction table
id
rule
status
restriction_role table
id
restriction_id
role_id
Run Code Online (Sandbox Code Playgroud)
此设置的原因是角色和限制实际上可以属于多个其他模型.在这种情况下,角色只能有1个限制.我通常会将其定义为
class Role extends Eloquent {
public function restrictions()
{
return $this->hasOne('Restriction');
}
}
Run Code Online (Sandbox Code Playgroud)
这显然不起作用,因为Laravel不知道连接此关系的数据透视表.我可以通过使用多对多关系来轻松实现这一点,但这并不是我的模型的工作原理.在文档中没有看到任何定义它的内容.有什么想法吗?
小智 7
我通过使用belongsToMany关系并为它定义自定义访问器来解决这个问题,如下所示:
public function foo()
{
return $this->belongsToMany(App\Bar::class);
}
public function getFooAttribute()
{
return $this->foo()->first();
}
Run Code Online (Sandbox Code Playgroud)
正如@deczo 在评论中所说的那样,belongsToMany() 是关于所有可以在这里工作的。first()如果您只需要一个结果但不能使用hasOne()关系,我建议使用该方法返回第一个结果。