我的所有项目都存在一个持续存在的问题,我需要帮助了解如何使其工作。
我认为=
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
是一个集合。
答案 0 :(得分:2)
请首先使用var_dump验证商店是否在提供对象。之后,您可以查看https://laravel.com/docs/5.6/queries了解更多详细信息。
答案 1 :(得分:2)
由于产品的用户很多,因此可以重构代码以使用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
是否为空或为null,以免遇到意外错误
答案 2 :(得分:2)
1)首先,您可以使用Injection来避免以下行:$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
答案 3 :(得分:2)
根据您的代码,此处$ 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();
}
答案 4 :(得分:0)
您应该尝试以下操作:
$product = Product::find($id);
$user = Product::where('user', $product->user)->get();
foreach($user as $rowdata){
$store = Store::where('user_id', $rowdata->id)->get();
}