繁体   English   中英

Laravel 5一对多雄辩的关系

[英]Laravel 5 one to many eloquent relationship

我有以下数据库表结构

users
  id
  name

articles
  id
  about_id
  author_id
  text

和以下用户:

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).

我的问题是,名为“ Article”的articles表的模型应该如何处理以下提到的关系。 我想访问文章对象以检索作者对象,例如:

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

并检索文章即将涉及的用户对象:

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

我不得不提到,我只有两个模型:文章和用户。

您的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');
    }
}

您也可以使用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