简体   繁体   中英

Laravel 5.5 - Pivot tables and hasMany relationship

Let's say I have this following. 4 tables and 3 models (Role, Posts, Users).

在此处输入图片说明

A User can be assigned many Roles and Roles can be assigned to many Users .

Posts can created with one Role per entry in the database.

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 . 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)

Here are my models thus far:

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

Forget about hasManyThrough , I was wrong.

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:

public function getPosts()
{
    return Posts::whereIn('role_id', $this->roles->pluck('id')->toArray())->get();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM