Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager load model using with but giving it another name - Laravel 5.2

Is it possible to use eager loading using the with method but giving it another name? Something like:

->with('documents as product', 'documents.documents as categories')

I have a documents table that can be product or categories, eager loading is working but not that friendly to retrieve the documents by just the document name instead of what it really is.

like image 473
Tim van Uum Avatar asked Jun 23 '16 08:06

Tim van Uum


People also ask

How to eager load models in Laravel?

Laravel’s ORM, called Eloquent, makes it trivial to eager load models, and even eagerly loading nested relationships. Let’s build on the Post model example and learn how to work with eager loading in a Laravel project. We will work with the project setup and then go through some eager loading examples more in-depth to wrap up.

What is an eager query in Laravel?

“Eager” here means that we’re associating all the related models for a particular result set using just one query, as opposed to having to run n queries, where n is the number of items in the initial set. You may also like: Build your own Laravel artisan commands for your project

What is eager loading in Salesforce?

At its core Eager Loading, is telling Eloquent that you want to grab a model with specific relationships that way the framework produces a more performant query to grab all the data you will need. By eager loading, you can take many queries down to just one or two.

What is eager loading in eloquent?

What is Eager Loading? At its core Eager Loading, is telling Eloquent that you want to grab a model with specific relationships that way the framework produces a more performant query to grab all the data you will need. By eager loading, you can take many queries down to just one or two.


1 Answers

This feature is currently not supported in any Laravel version. Your best bet is to duplicate your relations and name them according to your needs. E.g.:

class Post extends Model
    public function documents() {
        return $this->hasMany(Document::class);
    }

    public function products() {
        return $this->hasMany(Document::class)
            ->where('type', 'product'); // Scope the query, if necessary
    }

    public function categories() {
        return $this->hasMany(Document::class)
            ->where('type', 'category'); // Would a Document really be of type 'category', though? Looks like a code smell.
    }
}

$postsWithAllDocs = Post::with('documents')->get();
$postsWithProductsOnly = Post::with('products')->get(); // Only eager load Documents of type 'product'

On a side note, you mention that a Document can be a product or category, which logically doesn't seem to make much sense. Part of the issue could probably be resolved by rethinking the structure of your database and relations.

like image 178
Ed B Avatar answered Oct 20 '22 04:10

Ed B