Laravel multiple hasmany relation limit issue - laravel

I have 3 collection pages,posts,comments and relation is
pages => hasmany => posts => hasmany =>comments
pages model relation
public function posts()
{
return $this->hasMany('App\Models\PostsModel', 'page_id');
}
posts model relation
public function comments()
{
return $this->hasMany('App\Models\CommentsModel', 'post_id')->limit(10);
}
Query
PagesModel::with('posts.comments')->get();
it supposes to take all page posts and 10 comments for each post,
but it skips results, Many posts have multiple comments but unable to get comments.
Any solution or a better approach. Thanks

There is no native support for this in Laravel.
I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit trait in both the parent and the related model.
class PostsModel extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class CommentsModel extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
Then you can apply ->limit(10) to your relationship.

Its a common question for which there is no easy answer. Read https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/ for an explanation

Related

How to get all records(related and non related) of Laravel belongsTo relationship?

How can I get all the records from the relationship? I mean not only the related records, but also the rest.
Let's say I have a post which belongs to some category. If I want to change the category of this post I need a list of all available categories. Can I get this list from the relationship?
The Post model:
class Post extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
}
The Category model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
}
In the PostsController I tried:
$postModel->category->find('all'); // Returns null
$postModel->category->all(); // Returns only the related categories
I know I can simply use the Category model in the PostsController, but I prefer to do it using the relationship.
If you feel you must use the relationship to get to the other model you could try:
$categories = $post->category()->getRelated()->get();

Laravel get collection of models where relation has value

I am trying to make a more elaborate registration form for my Laravel web app.
I have a Category, Question and Survey model.
A category hasMany Question's and a Question belongsTo a Survey.
Category class:
public function questions()
{
return $this->hasMany('App\Question');
}
public function getUsingAttribute()
{
return $this->questions->contains('survey_id', Survey::current()->id);
}
I do currently have a using attribute in my Category class but I would like to make this a scope.
To be clear, the expected return of Category::using->get() would return all Category where at least one of the questions has a survey_id of Survey::current()
I would do it with one of the the methods available to query a relationship existence, specifically the whereHas() method:
return $this->whereHas('questions', function ($query){
$query->where('survey_id', Survey::current());
});
What about
return $this->questions->where('survey_id', Survey::current()->id);

Laravel 5.1 hasManyThrough Pivot table

I have model many to many relation like. I want to relate State and Category through pivot table CategoryNews.
Category model
class Category extends Model
{
public function news() {
return $this->belongsToMany('App\News');
}
}
News model
class News extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
public function state()
{
return $this->belongsTo('App\State');
}
}
and the State model
class State extends Model
{
public function news() {
return $this->hasMany('App\News');
}
}
I want to select the news related to the state where cat_type=2(from category table)
i tried
$slide_news = State::whereHas('news.categories',function($query){ $query->where('categories.cat_type',2);})
->with(array('news'=>function($query){
$query->orderBy('created_at', 'desc');}
))->where('id',$id)->first();
but the cat_type filter is not working. I also tried hasManyThrough but i don't know how to implement it with Pivot Table
Please help
There is a Laravel 5.5 composer package that can perform multi-level relationships (deep)
Package:
https://github.com/staudenmeir/eloquent-has-many-deep
Example:
User → belongs to many → Role → belongs to many → Permission
class User extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function permissions()
{
return $this->hasManyDeep(
'App\Permission',
['role_user', 'App\Role', 'permission_role'], // Pivot tables/models starting from the Parent, which is the User
);
}
}
Example if foreign keys need to be defined:
https://github.com/staudenmeir/eloquent-has-many-deep/issues/7#issuecomment-431477943
To the moderators:
DO NOT DELETE MY ANSWER
It took me two god damn days to solve this issue, and I was so happy i found the solution that i want to let the world know
Notice that my answer was upvoted, yet you deleted it.
The question's title is regarding: hasManyThrough Pivot table for Laravel, and my answer gives just that, a solution to perform hasManyThrough equivalent on Pivot Tables
The question was 3 years old, and let's admit no one wants a solution specific to the question, because we've all got our own.
If I were you, I'd prefer a generic answer.

Laravel 4 - Display username based on ID

I have a posts and a users table.
In the posts table, i have a posts_author which is the ID of the user from the users table.
Is there an easy way to display the email address of the user, which is in the users table?
Cheers,
As long as you've set your relationships up it should just be a simple query.
http://laravel.com/docs/eloquent#relationships
Look at the one to many relationships.
(1 User, Multiple posts)
Remember to set the inverse of the relationship up also
If your model has the right relationships then should be as simple as $post->author->email().
You must tweak the author relationship because Eloquent assumes the key will be named author_id.
// Post
public function author() {
return $this->belongsTo('Author', 'posts_author');
}
// Author
public function posts() {
return $this->hasMany('Post');
}
Remember to use eager loading in case you are retrieving emails from more than one post object, or you will end up with n+1 queries.
Providing that you've configured the relationships properly, it should be pretty easy.
Post Model:
class Post extends Eloquent
{
protected $table = 'posts';
public function author()
{
return $this->belongsTo('User', 'posts_author');
}
}
Then User Model:
class User extends Eloquent
{
protected $table = 'users';
public function posts()
{
return $this->hasMany('Post', 'posts_author');
}
}
Then when loading the post you can do the following.
$post = Post::with('author')->find($id);
This will tell Eloquent to join on the users table and load the user data at the same time. Now you can just access all of the user information like this:
$post->author->username;
$post->author->email;
$post->author->id;
// etc etc
Obviously this is just a skeleton, but the assumption is that you have the rest setup.

Eloquent many to many self/meta relationship $this->hasMany($this)

So I am working on a project in Laravel 4, and I am wondering how to do a many to many relationship on a single Model. I think comments should be able to belong to other comments (replies) Or at the very least replies should be able to have many replies.
I think that the way I would build the model would be:
Class Comment extends Eloquent {
public function comments() {
// assuming my comments table has an $id column and a second $comment_id table
// do I even need to specify the column name?
return $this->hasMany('Comment', 'comment_id');
}
public function comment() {
return $this->belongsTo('Comment');
}
}
Where can I look for more documentation about this, or what is the Laravel way to achieve what I am trying to achieve?

Resources