用户和评论模型之间的关系

时间:2014-01-04 23:10:56

标签: laravel laravel-4

我一直在不同模特之间建立关系,但出于某种原因,我无法让这个模型起作用。我尝试了在谷歌上找到的所有东西,但没有运气。

我想在Comment和User模型之间创建关系。任何用户都可以发表很多评论,我需要使用评论者的电子邮件地址。

基本上,这个:

$comments->user->email

我的数据库如下所示:

userdata
--- id
--- username
--- email

comments
--- id
--- username
--- comment

userdata.usernamecomments.username应该相互关联。

我将数据传递给这样的视图:

Comment::with('user')->where('on', $news->id)->orderBy('id', 'DESC')->take(10)->get()

无论我尝试什么,我都无法让它发挥作用。没有创建关系。也许我遇到了一个奇怪的laravel bug?

这些是我的模特:(我写了默认的模型,因为我把它们搞得太多了,尝试了不同的方法)

class Comment extends Eloquent {

    public static $key = 'id';
    protected $table = 'comments';
    public $timestamps = true;
}


class User extends Eloquent implements UserInterface, RemindableInterface {
    protected $table = 'userdata';
    public $timestamps = false;

    //It contains necessary imports and methods, I cutted them off for stackoverflow
}

有人知道我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

在正常的数据库方案中,文档写为here。在你的情况下,这应该工作:

// Model: Comment
public function user()
{
    //belongsTo('User', 'local_key', 'parent_key'); so:
    return $this->belongsTo('User', 'username', 'username');
}

//Then get this
Route::get('/test', function()
{
    return Comment::find($id)->user->email;
});

答案 1 :(得分:0)

此代码$comments->user->email不起作用。

$comments是一系列评论。它不包含对用户的任何共享引用,您必须提取特定注释并阅读相关用户。

您是否已将belongsTo()方法添加到评论模型中?