【发布时间】:2017-11-16 02:39:22
【问题描述】:
假设我在 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 是将Users 与Roles 连接起来的数据透视表。而Posts 只能与一个角色相关联(技术规范要求)。
如何在 Eloquent 中建立关系,以便我可以让用户通过分配给他们的 Roles 获得他们可以看到的每一个 Post?
我已经修改了 Laravel 关系文档的查看,并且我看到了 Many-to-Many 多态关系,但似乎我不断得到:SQLSTATE[42S02]: Base table or view not found: 1146 Table 或某种形式。
我做错了什么?
【问题讨论】:
-
你能分享你的模型吗?确切地说,您如何定义关系
-
@Hamoud 完成。对此感到抱歉。