Reputation: 1390
I'm trying to fetch covers of the books that belongs to an author. So far, so good. But it generates a separate query for each book and takes 2 seconds to load a page, I think I'm doing something wrong.
I use eager loading with my comments table (a comment belongs to a user), but since I use polymorphic relations with images table (a image can belong to different kind of other tables, such as user, thing, or group, so I can't use foreign keys in images table since it's not a right convention), I couldn't find a way to achieve the same thing this time.
Image Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
Person Model (Author)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Person extends Model {
public function books()
{
return $this->belongsToMany('\App\Models\Thing', 'person_thing');
}
Thing Model (Books)
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Thing extends Model {
public function cover() {
return $this->morphMany('\App\Models\Image', 'imageable');
}
}
Controller
$findBooks = Person::with(array('books' => function($query)
{
$query->groupBy('original_name');
}))->find(52957);
$allbooks = $findBooks->books;
return view('frontend.index')->with('allbooks', $allbooks)
}
Current View
@foreach($allbooks as $allBooks)
@foreach($allBooks->cover as $value)
<img class="hund" src="{{$value->link}}" alt="">
@endforeach
@endforeach
Upvotes: 2
Views: 1840
Reputation: 45
$query->with([
'child' => function ($q) {
$q->where(’someCol', ’someVal’); //constraint on child
},'child.grandchild' => function ($q) {
$q->where(‘someOtherCol’, ‘someOtherVal’); //constraint on grandchild
}
]);
Upvotes: 2
Reputation: 19
I don't think your problem is with eager loading or morph to many if your page takes 2s to load, ,Did you install laravel/debugbar to see exactly what takes 2 sec or how many queries u run?
Upvotes: 0