gpt4 book ai didi

php - laravel Eloquent 多个表,其中标准

转载 作者:行者123 更新时间:2023-12-05 06:32:43 24 4
gpt4 key购买 nike

我花了两天时间试图解决这个问题,但没有成功。我有 3 个表,类别,项目和相关项目,每个项目都在一个类别下,类别可以有很多项目,这部分工作正常,现在问题在相关项目中,我在表 realteditems 3 个字段中,id(只是autoincrement), ritemf_id,riteml_id 指的是 items 表中的 item_id。我想要做的是显示项目及其详细信息以及与该项目相关的项目,这意味着如果 item1 有很多真实的项目,例如 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');
}
}

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

 @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

enter image description here

最佳答案

relateditems()在我看来,Item 模型中的定义不正确,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从集合类中使用方法对不在数据库端的检索数据进行分组

关于php - laravel Eloquent 多个表,其中标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51121685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com