【发布时间】:2015-09-28 08:29:52
【问题描述】:
我想在 Laravel 4 中做一个论坛(不要问我为什么,哈哈)。
但是,我想在其中安装一个 RBAC 系统,这样我就可以显示用户颜色等...
问题是,它不是很好用..
我得到了什么:
ForumController
public function thread($id)
{
$thread = ForumThread::with('role')->find($id);
if ($thread == null)
{
return Redirect::route('home')->with('fail', "That thread doesn't exist.");
}
$author = $thread->author()->first()->username;
$role_id = $thread->author()->first()->role_id;
$role_id2 = $thread->comments()->first()->author_id;
$color = Role::where('id', '=', $role_id)->first()->role_colour;
$color2 = User::where('user.id', '=', $role_id2)->join('roles', 'roles.id', '=', 'user.role_id')->join('comments', 'comments.author_id', '=', 'user.id')->first()->role_colour;
return View::make('forum.thread')->with('thread', $thread)->with('author', $author)->with('color', $color)->with('color2', $color2);
}
所以我想让$color2 工作。
现在他只显示第一个帖子的第一个值。
所以也许 ID 4 是第一个发表评论的人,它将采用 ID 为 4 的用户的 role_id。
但我想获得每张评论海报的颜色,以便正确显示。
Database schemes:
user:
roles
comments
希望有人可以帮助我:)
编辑
我的模型:
<?php
class ForumThread extends Eloquent
{
protected $table = 'threads';
public function group()
{
return $this->belongsTo('ForumGroup');
}
public function category()
{
return $this->belongsTo('ForumCategory', 'category_id');
}
public function comments()
{
return $this->hasMany('ForumComment', 'thread_id');
}
public function author()
{
return $this->belongsTo('User', 'author_id');
}
public function role()
{
return $this->hasMany('Role', 'id');
}
}
<?php
class ForumComment extends Eloquent
{
protected $table = 'comments';
public function group()
{
return $this->belongsTo('ForumGroup');
}
public function category()
{
return $this->belongsTo('ForumCategory');
}
public function thread()
{
return $this->belongsTo('ForumThread');
}
public function author()
{
return $this->belongsTo('User');
}
public function role()
{
return $this->hasMany('Role', 'id');
}
}
【问题讨论】:
-
您是否在迁移和模型中设置了外键?
-
是的,我想是的。我并不真正使用 migrate 功能,我更喜欢手动创建我的数据库。但我仍然使用正确的 sql 数据库结构。
-
我的模型有belongsTo和hasMany等...不知道你是不是这个意思?
-
所以评论有一个作者,他的角色有颜色?您应该在评论上指定一个 author() 函数,即 belongsTo,在作者 (User) 上指定一个 role() 函数,即 hasOne 并使用 Comment::where('x', 'y')->author()-> 进行查询角色()->获取()。您不需要使用 join。
-
是的,评论有 author_id wicj 必须链接到用户 ID。它必须从 usertable 中获取 role_id,然后从角色表中获取 role_colour 值。您能否在答案中写下您的最后评论?因为我不是很懂……
标签: php laravel join laravel-4 roles