想知道是否有可能通过 eloquent 有更好的方法轻松地从数据库中获取数据?以下是我通常使用的代码,并考虑让所有记录与 shopID 匹配,但在循环中的过滤和访问效率低下。
$add1 = ShopMeta::where('shopId', '=', $theID)->where('metadataKey', '=', 1015)->firstOrFail();
这样做的好处是我可以使用以下内容而不是 foreach 循环访问成员。
$add1->metadataValue;
有没有更好的方法来完成获得所有价值的工作?
这就是作用域查询的用途。
只需使用whereIn
:
$add1 = ShopMeta::where('shopId', '=', $theID)
->whereIn('metadataKey', array(1015, 1016))
->get();