[英]Laravel 5.5 - Pivot tables and hasMany relationship
Let's say I have this following. 假设我有以下关注者。 4 tables and 3 models (Role, Posts, Users). 4个表格和3个模型(角色,帖子,用户)。
A User
can be assigned many Roles
and Roles
can be assigned to many Users
. 可以为一个User
分配许多Roles
并且可以将Roles
分配给许多Users
。
Posts
can created with one Role
per entry in the database. Posts
可以与一个创建Role
在数据库中每个条目。
What I need help with 我需要什么帮助
I want to be able to grab a list of all posts of a user from their associated roles. 我希望能够从其相关角色中获取用户的所有帖子的列表。 So by calling auth()->user()->getPosts()
, I should get all Posts
from Roles
that are attached to a User
. 因此,通过调用auth()->user()->getPosts()
,我应该从附加到User
Roles
中获取所有Posts
。 I thought I could use hasManyThrough
but I don't see it can help my case as I get: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'field list' (SQL: select
posts .*,
roles .
user_id from
posts inner join
roles on
roles .
id =
posts .
role_id where
roles .
user_id = 1)
我以为可以使用hasManyThrough
但是在获得以下信息时,我看不到它能对我的情况有所帮助: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'field list' (SQL: select
帖子.*,
角色.
user_id说明from
帖子inner join
角色on
的角色.
ID =
职位.
ROLE_ID where
角色.
USER_ID = 1)
Here are my models thus far: 到目前为止,这是我的模型:
User.php user.php的
<?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',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function posts()
{
return $this->hasManyThrough(Posts::class, Role::class);
}
}
Role.php Role.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
Posts.php Posts.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model
{
public function roles()
{
return $this->hasMany(Role::class);
}
}
Clone this problem here: https://github.com/naknode/eloquent-help 在这里克隆此问题: https : //github.com/naknode/eloquent-help
Forget about hasManyThrough
, I was wrong. 忘了hasManyThrough
,我错了。
Here how you can do it: 这里是你怎么做的:
$user = User::with('roles')->first();
$userPosts = Posts::whereIn('role_id', $user->roles->pluck('id')->toArray())->get();
return $userPosts;
If you want to get the posts by calling auth()->user()->getPosts()
add the following method to your User model: 如果要通过调用auth()->user()->getPosts()
来获取帖子,请在用户模型中添加以下方法:
public function getPosts()
{
return Posts::whereIn('role_id', $this->roles->pluck('id')->toArray())->get();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.