pdphilip / laravel-elasticsearch

Laravel Elasticsearch: An Elasticsearch implementation of Laravel's Eloquent ORM
https://elasticsearch.pdphilip.com/
MIT License
94 stars 17 forks source link

Creating a new record does not return relationships #52

Closed singercrazy closed 2 weeks ago

singercrazy commented 2 weeks ago

Is your feature request related to a problem? Please describe. I have a Post model. Those posts are stored in my elasticsearch instance. Each post has a user field with a user id. When creating a record or using the find method, the relationships are not loaded. A workaround is to do something like this

Post::where('_id', $post->_id)->first()

Describe the solution you'd like Return relationships where you would expect them to be returned.

pdphilip commented 2 weeks ago

Laravel inherently works by lazy loading related records, and so does this package. This is by design. As soon as you try to chain into the user record from your post record, it will load the related user model, assuming it exists. ex:

$post = Post::find($post->_id);  //Equivalent to Post::where('_id', $post->_id)->first()
$email = $post->user->email;  //At this point, it will load the model and get the user data for you.

If you want to eager load your related models, then use with(): https://laravel.com/docs/5.2/eloquent-relationships#eager-loading

$post = Post::where('_id', $post->_id)->with('user')->first();

I've assumed you've defined your belongsTo relationship properly: https://elasticsearch.pdphilip.com/es-mysql