Alexandru Alexandru - 2 months ago 18
PHP Question

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

Answer

Your Article model should look like this

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

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