将版主添加到论坛类别

时间:2015-10-05 22:36:03

标签: php mysql laravel laravel-5 eloquent

我正在尝试将用户指定为论坛类别的版主。目前,我只是尝试显示用户可以添加版主subreddit/{id}/moderators并显示subreddit名称的路线。

为此,我得到No query results for model [App\Subreddit]

我一定搞砸了桌子之间的关系。

我的桌子

#users: id, name, email...
#subreddits: id, name, user_id...
#moderators: id, user_id, subreddit_id

routes.php文件

Route::get('subreddit/{id}/moderators', [
    'as' => 'moderators',
    'uses' => 'ModeratorsController@create'
]);

Moderator.php模型

class Moderator extends Model
{
    protected $table = 'moderators';

    protected $fillable = ['user_id', 'subreddit_id'];

    public function subreddit() {
        return $this->belongsToMany('App\Subreddit');
    }

    public function user() {
        return $this->belongsTo('App\User');
    }
}

User模型中,我有hasManyThrough

public function moderators() {
    return $this->hasManyThrough('App\Moderator', 'App\Subreddit');
}

Subreddit模型中

public function moderators() {
    return $this->hasMany('App\Moderator');
}

然后在ModeratorsController我有以下create()方法

public function create(Moderator $moderator, Subreddit $subreddit, User $user)
{
    $subreddit = Subreddit::with('user')->findOrFail($subreddit->id);

    return view('user/moderators')->with('subreddit', $subreddit)->with('user', $user)->with('moderator', $moderator);
}

如果我将findOrFail更改为firstOrFail,它会让我获得数据库中的第一个subreddit,但我不想要第一个,我想要的是我想要添加版主的确切版本

1 个答案:

答案 0 :(得分:1)

class User extends Model{
    public function canModerate(){ //name this as you wish
        return $this->belongsToMany('App\Subreddit','moderators');
    }
    public function subreddits(){
        return $this->hasMany('App\Subreddit');
    }
}

class Subreddit extends Model{
    public function moderators(){ // name this as you wish
        return $this->belongsToMany('App\User','moderators');
    }

    public function creator(){
        return $this->belongsTo('App\User');
    }
}

id表中删除moderators,您不需要Moderator类。 可以找到其他文档here

修改RouteServiceProvider::boot方法并添加以下行:

$router->model('subreddit', 'App\Subreddit');

可以找到文档here

您的路线应如下:

Route::resource('subreddit.moderator','ModeratorsController');

网址应如http://localhost/subreddit/{subreddit}/moderator/create

最后控制器方法应该是:

public function create(Subreddit $subreddit)
{
    $user = $subreddit->creator;
    $moderators = $subreddit->moderators()->get();
    return view('user/moderators')->with(compact('subreddit','user','moderators'));
}