简体   繁体   English

laravel论坛模型关系

[英]laravel model relations for forum

I'm currenty making a forum in Laravel, just for the sake of learning, but I can't get my relations working well. 我目前正在拉拉韦尔(Laravel)建立一个论坛,只是为了学习,但我的关系无法正常运转。

I have a Thread, Post and User model. 我有一个线程,帖子和用户模型。

I've tried the following: 我尝试了以下方法:

class User {
    public function thread() {
        return $this->hasMany('Thread');
    }

    public function post() {
        return $this->hasManyThrough('Thread', 'Post');
    }
}


class Thread {

    public function post() {
        return $this->hasMany('Post');
    }

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

class Post {

     public function thread() {
        return $this->belongsTo('Thread');
     }

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

With this method I can get a specific thread, and the posts that belong in it. 通过这种方法,我可以获得特定的线程以及其中的帖子。 But I can't grab the user who has posted the post in the thread. 但是我无法抓住在帖子中发布帖子的用户。

I hope my problem is clear enough for you. 希望我的问题对您足够清楚。 Any help would really be appreciated. 任何帮助将不胜感激。

For clarity I suggest you name your relations singular for hasOne/belongsTo and plural for belongsToMany/hasMany 为了清楚起见,我建议您将关系单数命名为hasOne / belongsTo,将复数命名为belongsToMany / hasMany

so on the User and Thread it will be: 因此在User和Thread上将是:

public function posts() ...

Now, this is in wrong order: 现在,这是错误的顺序:

class User {
  public function posts() {
    // return $this->hasManyThrough('Thread', 'Post'); // wrong, change to:
    return $this->hasManyThrough('Post', 'Thread');
  }
}

Apart from that your relations look good, so you should be able to do this: 除此之外,您的关系看起来不错,因此您应该能够做到这一点:

$thread = Thread::with('posts.user')->find($threadId); // eager load relations
$thread->posts; // Eloquent Collection of Post models
foreach ($thread->posts as $post)
{
  $post->user; // author's User model
}

And by the way you can always have a look at the Laravel.io source: https://github.com/LaravelIO/laravel.io/ 而且,您可以随时查看Laravel.io的源代码: https : //github.com/LaravelIO/laravel.io/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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