包含两个外键

时间:2017-08-05 14:19:01

标签: laravel relationship

我有以下SQL表格,例如:

    guards
    guard_id guard_name guard_type

    roles
    role_id role_name security_priviledge

    guard_roles
    gr_id guard_id role_id

我如何在Laravel中定义这种关系?

1 个答案:

答案 0 :(得分:1)

您必须定义两个模型,App / Guard.php和App / Role.php,并定义他们的多对多关系。例如:

在App / Guard.php上:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Guard extends Model
{
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

在App / Role.php上:

namespace App;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function guard()
    {
        return $this->belongsToMany('App\Guard');
    }
}