Kin
Kin

Reputation: 4596

How to map Eloquent with other tables?

This is the first time when i use ORM, so i wondering if it is possible to map it to other tables...

For example i have currently logged user. It is connected to the POSTS table through links table. For example if i want to select posts i do sql like this:

SELECT
    `posts`.`id`', `posts`.`Name`, `posts`.`Description`
FROM
    `links`,
    `posts`
WHERE
    `links`.`user_id` = 1 AND `links`.`post_id` = `posts`.`id`

How to extend Eloquent that if i request Posts::all() it would return posts only for current user...

Upvotes: 0

Views: 1501

Answers (2)

Razor
Razor

Reputation: 9855

You can define a query scope in your POST modal

public function scopeOfUser($query,$user_id)
{
    return $query->join('links', 'links.post_id', '=', 'posts.id')
       ->where('links.user_id', '=', $user_id)
       ->select('posts.id', 'posts.Name', 'posts.Description');
}

Then use it like this:

$posts = POST::OfUser(1)->get();

Upvotes: 2

menjaraz
menjaraz

Reputation: 7575

Your post is a bit confusing but I hope my answer addresses it as you expect.

Warning:

Please refer to Laravel's (Many to Many) Relationship documentation for details.

To make things simple and comply with the Laravel convention, I strongly suggest you to use post_userinstead of link as the pivot table (post_user table should have user_id and post_id as columns).

You don't have to define a corresponding pivot model (that's the convention).

The following models are meant to map to respectfully the tables users and posts.

User Model:

in app/model/user.php (already there, just add the relationship definition)

class User extends Eloquent {

    ...

    public function posts()
    {
        return $this->belongsToMany('Post');
    }

    ...

}

Post Model:

in app/models/post.php (to be created of course).

...

class Post extends Eloquent {

    public function users()
    {
        return $this->belongsToMany('User');
    }

}

...

Retrieval of a user's posts:

Usually, you do the following in Laravel to get the current logged user:

$user = Auth::user(); // a User model / record

Assuming $user is of type User (Model), you can retrieve all its posts using:

$user->posts(); // a Collection

Upvotes: 2

Related Questions