-
Notifications
You must be signed in to change notification settings - Fork 11.6k
Closed
Description
- Laravel Version: 5.6.18
- PHP Version: 7.2.2
- Database Driver & Version: MySQL 5.7.19
Description:
I try to load a nested relationship which contains a where
clause on declaration using model's attributes. Since this models are not instantiated yet, the value of the property is null
because it's not pulled from DB yet.
Steps To Reproduce:
// App\Models\Page.php
public function contents()
{
return $this->hasMany(PageContent::class, 'target_id');
}
// App\Models\PageContent.php
public function route()
{
return $this->belongsTo(Route::class, 'target_id', 'target_id')
->where('language', $this->language);
}
// routes/web.php
Route::get('test', function () {
$page = \Origin\Models\Page::with('contents.route')->find(1);
dd($page->contents->first()->route); // null
});
Route::get('test-with-results', function () {
$page = \Origin\Models\Page::with('contents')->find(1);
dd($page->contents->first()->route); // Route model
});
The query performed with the eager loading is
select * from `routes` where `language` is null and `routes`.`target_id` in ('1')
because at the time of eager loading the nested relation routes
, the contents
models hasn't been instantiated first.
I tried with
->whereRaw('language', 'pages_content'.language')
but didn't work either.
Very appreciated for a solution to this or an alternative if it's not possible at the moment.
Thank you very much.
Metadata
Metadata
Assignees
Labels
No labels