我有以下数据库表结构
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 = Article::find(1);
$article->author;
并检索文章的用户对象:
$article = Article::find(1);
$article->about;
我必须提到我只有两个模型:文章和用户。
答案 0 :(得分:3)
您的文章模型应如下所示
class Article extends Model {
public function author() {
return $this->belongsTo("App\User", 'author_id');
}
public function about() {
return $this->belongsTo("App\User", 'about_id');
}
}
答案 1 :(得分:0)
您也可以使用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');
}
}
答案 2 :(得分:0)
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');
}
}