Laravel Eager Load with dynamic constraints

不想你离开。 提交于 2019-12-24 06:39:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!