我是第一次开发在线电子商务,目前,我无法遍历我的收藏。
商店的每件商品都归类为商品类别。我的关系低于
分类
public function items()
{
return $this->belongsToMany('App\Item','category_item','category_id','item_id')
->withTimestamps();
}
项
public function categories()
{
return $this->belongsToMany('App\Category','category_item','item_id','category_id')
->withTimestamps();
}
此代码可以获取组及其产品。我尝试循环获取如下所示的产品名称,但它只显示数据库中最后一个产品的名称。
为什么会这样?
ItemController
//获取产品类别的ID并在网格表中显示所有产品
$items_in_table = Category::whereIn('id',$request->get('product_category'))->with('products')->get();
foreach($items_in_table as $item)
{
return $item->name;
}
更新
$temp
foreach($items_in_table as $item)
{
temp = $item;
}
返回$ temp
响应
{" ID":2"标题":"货运"" no_of_contacts":0," USER_ID&# 34;:1," created_at":" 2018-04-15 23:55:30"," updated_at":" 2018-04-15 23:55:30""的项":[{" ID":1,"名称":&# 34; AirBag","电话":" 0247878234"," group_id":null," user_id":1,&# 34; created_at":" 2018-04-16 00:14:20"," updated_at":" 2018-04-16 05:31:05&#34 ;,"枢轴" {" GROUP_ID":2" CUSTOMER_ID":1," created_at":" 2018-04 -16 05:33:08"," updated_at":" 2018-04-16 05:33:08"}}
答案 0 :(得分:0)
也许你需要把它放在一个数组然后旋转它
$items_in_table = Category::whereIn('id',$request->get('product_category'))->with('products')->get();
$name = [];
foreach($items_in_table as $item)
{
$name[] = $item->name;
}
return $name;
答案 1 :(得分:0)
foreach不会操纵数组的值
一些可能的解决方案:
Use a reference,这会更改$ items_in_table
中的值 foreach($items_in_table as &$item)
{
$item = $item->name;
}
Use map(因为它是一个Laravel集合),这也会改变数组
$items_in_table->map(function ($item) {
return $item->name;
})
答案 2 :(得分:0)
让我们先定义我们的关系
<强>分类强>:
public function items()
{
return $this->belongsToMany('App\Item')
->withTimestamps();
}
<强>物品强>:
public function categories()
{
return $this->belongsToMany('App\Category')
->withTimestamps();
}
然后在你的控制器中:
$items_in_table = Category::with('items')->get();
$names = [];
foreach($items_in_table as $category) {
foreach($category->items as $item) {
$names[] = $item->name;
}
}
dd($names);