[英]I have a problem with foreach understanding laravel 5.6
我的所有项目都存在问题,我需要帮助了解如何使其工作。
在我看来=
URL = mysite.com/product/40
所以这里的产品ID是40
在视图中,我正在做一个foreach循环,以显示所有拥有此产品的商家。 我们有很多商家有很多产品,所以这是一个多对多的关系。
现在在我的控制器上
$product = Product::find($id); // to find the product
$users = $product->users; // here the user is the merchant that have the product
$store = Store::where('user_id', $user->id)->value('social');
在这里我得到错误:
试图获得非对象的属性
所以我想访问控制器中每个商家的商店我该怎么做? 因为现在$user
是一个集合。
请首先使用var_dump验证商店是否正在提供对象。 之后,您可以查看https://laravel.com/docs/5.6/queries以获取更多详细信息。
您可以重构代码以使用whereIn()
查询构建器方法,因为您有许多产品用户。 你会有类似的东西:
$product = Product::find($id); // to find the product
$users = $product->users->pluck('id');
$stores = Store::whereIn('user_id', $users->all())->value('social');
这意味着您的$ stores变量将包含用户拥有的那些商店。
PS:请务必检查
$users
是否为空或为空,这样您就不会遇到意外错误
1)首先你可以使用注入来避免这一行: $product = Product::find($id);
public function your_controller_methon(Product $product) {}
Laravel将自动为您完成这个技巧,$ product已经包含Product对象。
2)如果你有关系,你应该做类似的事情:
$product->stores
- 检索product_id列中包含特定产品的所有商店。 你可以这样做: $product->stores()->pluck('social');
检索具有特定产品的所有商家的社交列表。
关于你可以在这里阅读的关系: https : //laravel.com/docs/5.7/eloquent-relationships
根据你的代码,这里$ user是一个单独的值,而不是一个集合。
更改:
$store = Store::where('user_id', $user->id)->value('social');
至
$store = Store::where('user_id', $user);
它会奏效。
要将$ user作为集合,请执行此类查询,以便返回如下数组:
$product = Product::find($id);
$user = Product::where('user', $product->user)->get();
这将返回此产品的用户集合。
然后执行foreach循环:
foreach($user as $rowdata){
$store = Store::where('user_id', $rowdata->id)->get();
}
你应该试试这个:
$product = Product::find($id);
$user = Product::where('user', $product->user)->get();
foreach($user as $rowdata){
$store = Store::where('user_id', $rowdata->id)->get();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.