简体   繁体   English

Laravel 5一对多雄辩的关系

[英]Laravel 5 one to many eloquent relationship

I have the following database table structure 我有以下数据库表结构

users
  id
  name

articles
  id
  about_id
  author_id
  text

And the following users : 和以下用户:

1 Alex
2 John

And 2 articles one written by (author_id) John(2) about (about_id)
Alex(1) and other written by (author_id) Alex(1) about (about_id)
John(2).

My question is how should does the model of articles table named "Article", should look like for the relationships mentioned below. 我的问题是,名为“ Article”的articles表的模型应该如何处理以下提到的关系。 I would like to access the article object for retrieving author object like : 我想访问文章对象以检索作者对象,例如:

$article = Article::find(1);
$article->author;

And to retrieve the object of the user that the article is about like : 并检索文章即将涉及的用户对象:

$article = Article::find(1);
$article->about;

I have to mention that i have only two models : Article and User. 我不得不提到,我只有两个模型:文章和用户。

Your Article model should look like this 您的Article模型应如下所示

class Article extends Model {
    public function author() {
        return $this->belongsTo("App\User", 'author_id');
    }

    public function about() {
        return $this->belongsTo("App\User", 'about_id');
    }
}

You can also use hasMany 您也可以使用hasMany

class Article extends Model {
    public function author() {
        return $this->hasMany("App\Author", 'author_id', 'id');
    }

    public function about() {
        return $this->hasMany("App\About", 'author_id', 'id');
    }
}
use App\User;
use App\Article;

class Article extends Model {

    public function author() {
        return $this->belongsTo(Article::class, 'author_id');
    }

    public function about() {
        return $this->belongsTo(User::class, 'about_id');
    }
}

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

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