Laravel 5.5 - 多态关系

时间:2017-11-15 18:06:36

标签: php laravel

假设我在Laravel中有四个表(模型):

user.php的

id - integer
name - string
<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'token_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function embeds()
    {
        return $this->hasManyThrough('App\Post', 'App\Role');
    }
}

UserRoles.php

id - integer
user_id - integer
role_id - integer
<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserRoles extends Pivot
{
    protected $guarded = [];

    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    public function user()
    {
        return $this->belongsToMany(User::class, 'user_id');
    }
}

Role.php

id - integer
name - string
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * Don't auto-apply mass assignment protection.
     *
     * @var array
     */
    protected $guarded = [];

    public function roles()
    {
        return $this->belongsToMany(UserRoles::class);
    }
}

post.php中

id - integer
title - string
body - text
role_id - integer
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Don't auto-apply mass assignment protection.
     *
     * @var array
     */
    protected $guarded = [];
}

如您所见,UserRoles是一个数据透视表,用于将UsersRoles连接起来。并且Posts只能与一个角色(tech spec req)相关联。

如何使Eloquent中的关系成为可能,以便用户可以通过Post分配给每个Roles用户?

我已经修改了Laravel Relationships文档,我看到Many-to-Many多态关系,但似乎我不断获得:SQLSTATE[42S02]: Base table or view not found: 1146 Table或某种类型。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

嗯,数据透视表确实需要一个模型。你需要四个表和三个模型。

你几乎把桌子弄好了。只需将UserRole表重命名为role_user即可关注Laravel convention

  

role_user表派生自相关模型名称的字母顺序,并包含user_id和role_id列。

以下是设置模型的方法:

// User.php

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function posts()
    {
        return $this->hasManyThrough(Post::class, Role::class);
    }

// Role.php

    public function users()
    {
        return $this->belongsToMany(User::class);
    }


    public function posts()
    {
        return $this->hasMany(Post::class);
    }