Laravel通过在一个对象中雄辩地进行边查询来从查询中获得结果
我有两张桌子:Laravel通过在一个对象中雄辩地进行边查询来从查询中获得结果,laravel,eloquent,Laravel,Eloquent,我有两张桌子: 主要专题介绍 所以这里我有“id”和“isEnabled” 儿童讲座 这里我有“id”、“isEnabled”和“idParent” 我想在中选择一个对象这是我的代码: 公共功能主滑块(主演示文稿$main演示文稿,子演示文稿$ChildPresentations) { $MainPresentations=MainPresentation::where('isEnabled',true)->get(); foreach($main演示文稿作为$main演示文稿){ $AnArr
公共功能主滑块(主演示文稿$main演示文稿,子演示文稿$ChildPresentations)
{
$MainPresentations=MainPresentation::where('isEnabled',true)->get();
foreach($main演示文稿作为$main演示文稿){
$AnArray[]=ChildPresentation::where([
['idParent',$main演示文稿['id']],
['isEnabled',true]
])->get();
}
返回$AnArray;
}
但结果是:
您所做的是对每个结果执行一个查询,当结果开始变大时,这可能会无效 你可以:
public function MainSlider()
{
$childPresentations = ChildPresentation::join('main_presentations','main_presentations.id','child_presentations.idParent')
->where('child_presentations.isEnabled', true)->where('main_presentations.isEnabled', true)->get();
return $childPresentations;
}
如果希望所有主演示文稿及其各自的子演示文稿,则仅启用子演示文稿
您可以利用Laravel关系和快速加载
首先,在main演示文稿中设置关系
在MainPresentation.php中
public function childPresentation {
return $this->hasMany('App\ChildPresentation', 'idParent', 'id');
}
您的主滑块功能将是:
(顺便说一句,如果覆盖了两个参数,不知道为什么会收到这两个参数,但这并不重要)
这将返回一个main演示文稿数组,其中包含一个child_演示文稿数组及其所有child
这转化为两个查询:
Select * from main_presentations where isEnabled = true;
Select * from child_presentations where isEnabled= true and id in (in the first query);
然后,当您编写->toArray()
注意:如果在您的MainPresentation模型中有一个$visible
数组,请确保将:'childPresentation'
添加到该数组中,否则toArray将不会将childs添加到父级
第二个注意事项:我建议在编写代码时遵循一些标准,通常函数名为camelCase
,变量名为camelCase
你想做什么?更清楚一点我不想那样,[我想要一个JSON数组的根目录单击此处我有一些错误:IMG1:IMG2您是只想要子演示文稿,还是想要主子演示文稿?我添加了另一个解决方案,一个是简单的查询,另一个是带有关系和急切加载的解决方案。@JustLearnCode很好想法谢谢,但我遇到了麻烦:请,您需要一些命名约定,阅读代码时会非常混乱。它会给出错误,因为对于每个主演示文稿,您都有多个子演示文稿。请检查此项
Select * from main_presentations where isEnabled = true;
Select * from child_presentations where isEnabled= true and id in (in the first query);