[英]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.