php - 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
解决方案
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
方法用于从集合类中对检索到的数据进行分组,而不是在数据库端
推荐阅读
- java - Atlassian Bamboo 构建 Docker 镜像时出现权限错误
- python - 为什么 LightGBM 回归 R 平方值是负数?
- nosql - CosmosDB 查询多个项目
- javascript - 想在我的 reactjs 中处理复选框的更改
- azure - 与客户端共享 Office 加载项
- debugging - 无法在 Blazor WASM 中命中断点
- php - 如何在laravel中的刀片模板上从当天减去天数?
- android - 如何创建/替换 Android.mk 文件以实例化 Notification.TvExtender()
- outlook - 在 Microsoft Teams [HOW] 中将状态设置为“专注”;MyAnalytics 焦点时间将状态设置为“忙碌”
- flutter - 使用 Flutter Downloader 插件,下载应用关闭后