1
votes

I have defined custom query inside my eloquent model and I'm wondering what is the best way to include its result when I get the model.

I know that there is the protected $with, but that accepts only relationships then there is $appends but that is for attributes and my query returns whole object and I don't know if it's good idea to include it as attribute.

Also, if there is way to do this inside a models method, I would like to hear about it, because I don't necessarily need to have this information on every model instance.

Looking forward to hearing your suggestions.

Edit: I am familiar with $with and relations. What I'm asking is how do I get something like this to eager load:

public function thisIsMyQuery()
{
    return DB::table('example')->where('const', '>', 3);
}
1

1 Answers

0
votes

If I understood correctly your need, you only want to eager load a relation. To do so, you have to define a relation inside your model, and add the name of the method, inside the $with array.

example :

// Inside your model class

class Post extends Model
{
    protected $with = ['comments'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// Usage

$post = Post::find(1)
$post->comments; // here are the related comments