如何在发送查看之前检查集合的关系数据
我有一个像这样的控制器方法:
public function awaiting()
{
$producers = Producer::where('producer_process',4)->get();
$producers_list = [];
foreach($producers as $producer){
if($producer->brand->brand_rejected == 0){
array_push($producers_list, $producer);
}
}
return view('admin.brands.awaiting', compact('producers_list'));
}
所以基本上在Producer
模型和模型之间存在一对一关系。 品牌
型号。
为了获取 makers_process
为 4 以及相关的 brand_rejected
字段的 brands
表记录的集合brands
表记录必须设置为0,我添加了一个array_push
并检查条件。
现在这工作正常并且正确显示了正确的数据,但我想知道,使用 Eloquent 关系执行此操作的简写方法是什么?
我的意思是,是否有任何用 Eloquent 关系编写的简洁且有用的方法可以在不使用 array_push 或另一个 foreach 循环的情况下完成此操作?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
whereHas
根据关系的存在来约束结果集。在这里,我们说我们只希望生产商的“product_process”字段设置为 4,并且其品牌的“brand_rejected”字段设置为 0:如果您希望这些生产商加载其品牌关系以供使用,您应该立即加载那。在
get
调用之前,您可以告诉它加载关系:Laravel 5.8 文档 - Eloquent - 关系 - 查询关系存在
whereHas
Laravel 5.8 文档 - 雄辩 - 关系 - 热切加载
with
You can use
whereHas
to constrain the result set based on the existence of a relationship. Here we are saying we only want producers that have the field 'produce_process' set to 4 and have a brand with a field of 'brand_rejected' set to 0:If you want these producers to have their brand relationship loaded to use you should eager load that. Before the
get
call you can tell it to load the relationship:Laravel 5.8 Docs - Eloquent - Relationships - Querying Relationship Existence
whereHas
Laravel 5.8 Docs - Eloquent - Relationships - Eager Loading
with
你可以试试这个:
You can try this:
当然,您可以将方法
与()
一起使用其中()
条款可以应用于关系示例
的某些条件,请检查此信息
我希望这很有帮助
Sure you can use the method
with()
also with thewhere()
clause to can apply some conditions to the relationshipExample
check this for more info
https://laravel.com/docs/9.x/eloquent-relationships#constraining-eager-loads
I hope it's helpful