Alexandru
Alexandru

Reputation: 117

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.

Upvotes: 0

Views: 1823

Answers (3)

Sonford Son Onyango
Sonford Son Onyango

Reputation: 49

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

Upvotes: 0

Dipak Dendage
Dipak Dendage

Reputation: 648

You can also use 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');
    }
}

Upvotes: 0

Margus Pala
Margus Pala

Reputation: 8673

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

Upvotes: 4

Related Questions