Pagination with relationships - laravel

I'm having problems returning the data for two relationships when using paginate.
$things = $this->model->with('fruits')->with('animals')->paginate(5, ['id, 'name']);
Returns the "things" I want but the "fruits" and "animals" arrays are empty.
To clarify, the relationships check out, things "has Many" fruits and also "has many through (fruits)" animals.
public function fruits()
{
return $this->hasMany('App\Fruit');
}
public function animals()
{
return $this->hasManyThrough('\App\Animal', '\App\Fruit');
}
I would like to be able to load "things" along with any relationships while being able to paginate the "things"

with() only tells Eloquent to pre-fetch the related models, so you can avoid the N+1 query problem. It does not mean that when you return the model, that information is also returned.
I would create an Eloquent Resource:
Class FruitResource extends \Illuminate\Http\Resources\Json\Resource {
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name
];
}
}
Class AnimalResource extends \Illuminate\Http\Resources\Json\Resource {
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name
];
}
}
Class ThingResource extends \Illuminate\Http\Resources\Json\Resource {
public function toArray($request) {
return [
'id' => $this->id,
'fruits' => FruitResource::collection($this->fruits),
'animals' => AnimalResource::collection($this->animals)
];
}
}
Once you created these resource, you can alter your controller to do the following:
$things = $this->model->with('fruits')->with('animals')->paginate(5, ['id, 'name']);
return ThingsResource::make($things);
By structuring your resources, you can easily get more control on what you return. Make life a lot nicer...

Related

Eager Loading vs Lazy Loading with API Resource

Could you please suggest which option I should use for the following example.
I'm currently building an API to get Places, Place model contains User and Location models.
Relationships are set like that:
class Place extends Model
{
protected $guarded = [];
public function createdBy()
{
return $this->belongsTo(User::class, 'created_by', 'id');
}
public function location()
{
return $this->belongsTo(Location::class);
}
}
Option 1: Lazy Loading:
public function getPlaces()
{
return Place::all()->get();
}
class PlaceResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'createdBy' => (new UserResource($this->createdBy)),
'location' => (new LocationResource($this->location)),
];
}
}
Option 2: Eager Loading:
public function getPlaces()
{
return Place::with([
'createdBy',
'location',
])
->get();
}
class PlaceResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'createdBy' => (new UserResource($this->createdBy)),
'location' => (new LocationResource($this->location)),
];
}
}
Logically thinking with the Eager Loading option data should loads quicker, right? I have tested both options for about 100 places but the loading time seems to be the same.
What's the right way (option to use) to load data quicker?
It is better to Eager Load those relationships when dealing with a result set like that. Since you are iterating through each record in that result set and accessing the relationship this would cause a N+1 issue otherwise. Since it is 2 relationships being accessed it would be (N*2) + 1 .

Laravel Algolia Scout, whereIn on relationships

I am working on a Laravel project. I am using Scout based on Algolia. But I struggling to apply whereIn on the relationships. I have 2 models as follow.
Place.php
class Place extends Model
{
use Searchable, Localizable;
protected $with = [
'images',
'phones',
'emails',
'categories'
];
protected $casts = [
'is_featured' => 'boolean'
];
public function categories()
{
return $this->belongsToMany(Category::class, 'place_category');
}
public function searchableAs()
{
return "places_index";
}
public function toSearchableArray()
{
$record = $this->toArray();
$record['_geoloc'] = [
'lat' => $record['latitude'],
'lng' => $record['longitude'],
];
$record['categories'] = $this->categories->map(function ($data) {
return [
'id' => $data['id'],
'en_name' => $data['en_name'],
'mm_name' => $data['mm_name'],
];
})->toArray();
unset($record['created_at'], $record['updated_at'], $record['latitude'], $record['longitude']);
unset($record['images'], $record['phones'], $record['emails']);
return $record;
}
}
Category.php
class Category extends Model
{
use Searchable;
protected $touches = [
'places',
];
public function places()
{
return $this->belongsToMany(Place::class, 'place_category');
}
}
Now, I am searching the Place models/ data filtering by category. As you can see, I have also indexed the categories with places in toSearchableArray method.
I am trying to achieve something like this.
Place::search($keyword)->whereIn('categories', ????);//how can I filter by the Ids here
How can I do that?

Is it correct to create different Api Resources for each request?

Will it be correct, if I create API RESOURCES for each request. And how to make a connection between three tables in Resources. For example:
class UserResource
public function toArray($request)
{
return [
'id'=>$this->id,
'name'=>$this->name
'work'=>WorkResource::collection($this->work)//relationship between USER and WORK
]
}
class WorkResource
public function toArray($request)
{
return [
'id'=>$this->id,
'title'=>$this->title
]
}
And in class UserResource I need to return from WORK only TITLE without ID, How I can do that?
I'm not sure if I got it right but $this->work seems singular while you are instanciating the resource using Resource::collection().
So my guess would be:
class UserResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'work' => new WorkResource($this->whenLoaded('work'))
];
}
}
class WorkResource
{
public function toArray($request)
{
return [
'title' => $this->title
];
}
}

Laravel API ResourceCollection WhenLoaded

I try to include a relationship in my resource array if it has been eager loaded, but don't get it working.
Anyone has an idea, how I can check the relationships in the ResourceCollection?
Database schema looks like this:
Here is my Post Model
class Post extends Model
{
function categories() {
return $this->belongsToMany('App\Category');
}
}
Here is my Category Model
class Category extends Model
{
function posts() {
return $this->belongsToMany('App\Post');
}
}
Here is my Post Controller
Class PostController extends Controller
{
public function index()
{
return new PostResourceCollection(Post::with("categories")->get());
}
}
Here is my Post ResourceCollection
class PostResourceCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection->transform(function($page){
return [
'type' => 'posts',
'id' => $page->id,
'attributes' => [
'name' => $page->title,
],
];
}),
//'includes' => ($this->whenLoaded('categories')) ? 'true' : 'false',
//'includes' => ($this->relationLoaded('categories')) ? 'true' : 'false',
];
}
}
Maybe too late, below solution is a workaround for this case:
return [
...,
'includes' => $this->whenLoaded('categories', true),
];
Loading custom attribute:
return [
...,
'includes' => $this->whenLoaded('categories', fn() => $this->categories->name),
];
You relationship is wrong, a post belongs to many categories while a category has many posts so change:
class Category extends Model
{
function posts() {
return $this->belongsToMany('App\Post', 'category_post');
}
}
to
class Category extends Model
{
function posts() {
return $this->hasMany('App\Post', 'category_post');
}
}
Now when you load the post you can load the categories also:
$posts = Post::with('categories')->get();
got it.. That was the missing piece. if anyone has a better solution for this it would be much appreciated.
foreach ($this->collection as $item) {
if ($item->relationLoaded('categories')) {
$included = true;
}

Filter and sort in gridview by related field (2 degrees away)

My model Order has the following functions:
public function getAccount()
{
return $this->hasOne(Account::className(), ['id' => 'account_id']);
}
public function getChairName()
{
return $this->account->chairName;
}
The problem is that chairName itself is a related field (Created here in another model Account):
public function getChair0()
{
return $this->hasOne(Category::className(), ['id' => 'chair']);
}
public function getChairName()
{
return $this->chair0->name;
}
In my OrderSearch model I am now trying to search and filter by the name of the chair. In Account the chair is stored with an id that is linked to the model Category.
I have been looking at this link but it didn't help me solve my issue:
http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/
MY OrderSearch model looks like this:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\OrderHistory;
[...]
class OrderHistorySearch extends OrderHistory
{
[...]
public $chairName;
[...]
public function rules()
{
return [
[...]
[['chairName'], 'safe'],
[...]
];
}
[...]
public function scenarios() { [...] }
public function search($params)
{
$query = OrderHistory::find();
$query->joinWith(['employee', 'account', 'item']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
[...]
$dataProvider->sort->attributes['chairName'] = [
'asc' => ['account.chair' => SORT_ASC],
'desc' => ['account.chair' => SORT_DESC],
];
[...]
$this->load($params);
if (!$this->validate()) { [...] }
$query->andFilterWhere([ [...] ]);
$query->andFilterWhere(['like', 'category.name', $this->chairName]);
return $dataProvider;
}
}
I reckon my mistake lies somewhere here:
$query->joinWith(['employee', 'account', 'item']);
The problem lies definitely in the fact that I am trying to join a table that is currently not joining.

Resources