问题
Can anybody please help me to understand why the following code is working
$x = $widget->objGallery->galleryItems()->with(array('captions' => function($query){ $query->where('locale', 'IT' );}))->get() ;
but when I am using a dynamic value
$id='11';
$x = $widget->objGallery->galleryItems()->with(array('captions' => function($query){ $query->where('locale', $id );}))->get() ;
is saying
Method Illuminate\View\View::__toString() must not throw an exception
回答1:
In fact it's hard to say because you haven't showed here relevant code, but the problem with code:
$x = $widget->objGallery->galleryItems()->with(array('captions' =>
function($query){ $query->where('locale', $id );
}))->get();
is that variable $id
is undefined here. You need to add use
to use if in closure, so the code should look like this:
$x = $widget->objGallery->galleryItems()->with(array('captions' =>
function($query) use($id) { $query->where('locale', $id );
}))->get();
You should change your environment to local and have turned on debugging, probably you would then know about this problem. Probably when correcting this code as I showed you won't have the error.
回答2:
You can't, if you want to query by a relationship you need to use whereHas.
This is, for the conception of eager loading, just clarify... With syntax fix on @Marcin Nabiałek's response, that where in the "with" function works only on the eager loading data, not in the main query.
来源:https://stackoverflow.com/questions/26542419/laravel-eager-load-with-dynamic-constraints