404error
404error

Reputation: 575

Picking the right type of relationship using Laravel and Eloquent

I have three tables in my database.

Posts

Authors

Categories

When viewing an Author page I want to be able to view all of the author's Posts and also the category of the post.

When viewing a Category index page I want to be able to view all of the Posts for that category and also include the Author with each Post.

When viewing a Post I want to be able to include the Category and Author

What type of relationship can I use to achieve this?

One to one, One to Many, Many to many, or polymorphic

Thanks in advance.

Upvotes: 1

Views: 1668

Answers (2)

Sagiruddin Mondal
Sagiruddin Mondal

Reputation: 5787

I have done something like this :

db table =

users : id name debates : id post user_id

now in model

class User extends SentryUserModel {


        public function debates()
    {
        return $this->hasMany('Debate', 'user_id');
    }
}

and

class Debate extends Eloquent {
    public function user()
    {
    return $this->belongsTo('User', 'id');
    }

}

now in query

$debate= Debate::find(1);

echo $debates->user->name;
echo $debates->user->id;

it is giving a null result.

Changing this two solve the problem . (Do now know why we cant use foreign key here. If anyone know this please do inform ).

class User extends SentryUserModel {

    public function debates()
{
    return $this->hasMany('Debate');
}

} and

class Debate extends Eloquent {
    public function user()
    {
    return $this->belongsTo('User');
    }

}

Upvotes: -1

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87789

You can create your relations like this:

class Post extends Eloquent {

    public funcion category()
    {
        return $this->belongsTo('Category');
    }

    public funcion author()
    {
        return $this->belongsTo('User');
    }

}

class Author extends Eloquent {

    public funcion posts()
    {
        return $this->hasMany('Post');
    }

}

class Category extends Eloquent {

    public funcion posts()
    {
        return $this->hasMany('Post');
    }

}

And then use them this way:

$author = Author::find(1);

foreach($author->posts as $post)
{
    echo $post->title;
    echo $post->author->name;
}

$category = Category::find(1);

foreach($category->posts as $post)
{
    echo $post->title;
    echo $post->author->name;
}

$post = Post::find(1);

echo $post->category->title;
echo $post->author->name;

Upvotes: 2

Related Questions