laravel-nestedset icon indicating copy to clipboard operation
laravel-nestedset copied to clipboard

Getting related models from other table with paginator

Open schel4ok opened this issue 5 years ago • 0 comments

I want to create query to output all posts belongs to one category with pagination of these posts. I did like below, but anyway on output I have simple Illuminate\Database\Eloquent\Collection of posts without paginator. How to do that?

In my models I have relations One category hasMany Posts. One post belongsTo one Category.

	public function getItemWithPostsWithPaginator($slug, $perPage = null)
	{
		$columns = ['id', '_lft', '_rgt', 'parent_id', 'title', 'slug', 'icon', 'description', 'image', 'metatitle', 'metakey', 'metadesc'];

		$postcolumns = ['title','slug','category_id','image','fulltext','created_at'];

		$result = $this
			->startConditions()
			->whereSlug($slug)
			->select($columns)
			->with(['posts' => function($query) use (&$postcolumns, &$perPage) {
				$query->select($postcolumns)
					  ->wherePublished(true)
					  ->orderBy('created_at', 'ASC')
					  ->simplePaginate($perPage);
				}])
			->first();

		return $result;
	}

If I do dd I can see in output collection with 11 Posts, though $perPage = 10 and total number of posts belongs to this category is 24. So it doesn't work as expected: 11 results instead 10 and no paginator object.

App\Models\NewsCategory {#838 ▼
  +timestamps: false
  #guarded: []
  #connection: "mysql"
  #table: "news_categories"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:12 [▶]
  #original: array:12 [▶]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [▼
    "posts" => Illuminate\Database\Eloquent\Collection {#905 ▼
      #items: array:11 [▼
        0 => App\Models\NewsPost {#925 ▶}
        1 => App\Models\NewsPost {#926 ▶}
        2 => App\Models\NewsPost {#927 ▶}
        3 => App\Models\NewsPost {#928 ▶}
        4 => App\Models\NewsPost {#929 ▶}
        5 => App\Models\NewsPost {#930 ▶}
        6 => App\Models\NewsPost {#931 ▶}
        7 => App\Models\NewsPost {#932 ▶}
        8 => App\Models\NewsPost {#933 ▶}
        9 => App\Models\NewsPost {#934 ▶}
        10 => App\Models\NewsPost {#935 ▶}
      ]
    }
  ]
  #touches: []
  #hidden: []
  #visible: []
  #fillable: []
  #pending: null
  #moved: false
}

If I replace simplePaginate with paginate I can see collection with 10 Posts, which is better, but anyway normal collection without paginator.

schel4ok avatar May 11 '20 19:05 schel4ok