Reputation: 4596
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
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
Reputation: 7575
Your post is a bit confusing but I hope my answer addresses it as you expect.
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_user
instead 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
.
in app/model/user.php (already there, just add the relationship definition)
class User extends Eloquent {
...
public function posts()
{
return $this->belongsToMany('Post');
}
...
}
in app/models/post.php (to be created of course).
...
class Post extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
}
...
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