首页 > 解决方案 > laravel 雄辩的多个表 where 条件

问题描述

我花了两天时间试图解决这个问题,但没有运气。我有 3 个表、类别、项目和相关项目,每个项目都在一个类别下,类别可以有很多项目,这部分工作正常,现在问题出在相关项目中,我在表 realteditems 中有 3 个字段,id(只是autoincrement), ritemf_id,riteml_id 指的是 items 表中的 item_id。我想要做的是显示项目及其详细信息和与该项目相关的项目,这意味着如果 item1 有很多 realted 项目,例如 item2,item3,item4 .. 所以需要像这样显示

item_title: item1

相关项目:

项目2

第 3 项

第 4 项

控制器

   $items = Item::orderBy('category_id', 'asc')->with('category')->get()->groupBy('category_id');

   $categories = Category::orderBy('category_id', 'asc')->get();

   return view('home',['items' => $items,'ritems' => $ritems,'categories' => $categories]);

物品模态

 public function category() 
  {
    return $this->belongsTo('App\Category', 'category_id');
   }
 public function relateditems() 
 {
 return $this->belongsTo('App\Relateditem', 'ritemf_id');       
  }

相关项模态:

 class Relateditem extends Model
  {
    protected $table="relateditems";
   protected $fillable=['ritemf_id','riteml_id'];
   protected $primaryKey='id';
   public $timestamps=false;
 public function items() 
 {  
    return $this->belongsTo('App\Item', 'item_id');
 }
 }

在刀片中显示其类别的项目(工作正常)

 @if (!empty($categoryItems->first()->category))        
 {{ $categoryItems->first()->category->category_name }} @else {{$category_id}} @endif

   @foreach($categoryItems as $item)
 {{$item->item_title}}
  ${{$item->item_price}}
 @endforeach
 @endforeach

在此处输入图像描述

标签: phplaravel

解决方案


relateditems()模型中的定义对我来说看起来不正确Item,项目可能有多个相关项目,那么这应该是hasMany/beongsToMany关联。

假设它hasMany 然后将您的项目模型更新为

public function relateditems()  {
    return $this->hasMany('App\Relateditem', 'ritemf_id');       
}

并急切地为每个项目加载您的相关项目

$items = Item::orderBy('category_id', 'asc')
             ->with(['category', 'relateditems'])
             ->get()
             ->groupBy('category_id');

我假设该groupBy方法用于从集合类中对检索到的数据进行分组,而不是在数据库端


推荐阅读