[英]Eloquent Laravel Fetch Data from multiple tables
我花了两天时间试图解决这个问题,但我不知道如何解决。
我有五张桌子
从视图中,单击类别按钮我必须获取他订购的所有具有相关类别的产品。
我有当前的模型:
产品 Model
class Product extends Model
{
public function categories() {
return $this->belongsToMany('App\Category');
}
public function orders() {
return $this->belongsTo('App\Order');
}
}
类别 Model
public function products() {
return $this->belongsToMany('App\Product');
}
订购 Model
public function products() {
return $this->belongsToMany('App\Product');
}
现在的问题是我不知道如何从当前表中获取数据。当我按下按钮时,我能够从Product
表中获取类别,但我想从Ordered_Products
中获取。 我实在想不通怎么做。
有了这个,我可以从 Product 中获取所有类别
if (request()->category) {
$products = Product::with('categories')->whereHas('categories', function ($query) {
$query->where('slug', request()->category);
})->get();
}
相反,我可以获取订购的产品。
$products = DB::table('order_product')
->join('products', 'order_product.product_id','=', 'products.id')
->where('order_product.user_id','=',$user_id)
->get();
对于后者,有更好的方法来做到这一点,这是肯定的。 如果这是一个愚蠢的问题,我很抱歉,但我对这个框架相当陌生。 我正在使用 Laravel 7.2。
基本上 Eloquent Model 不鼓励加入表来检索数据。 它应该仅用于过滤结果(因此您需要使用->select('original_table.*')
删除其他表的字段)
在这种情况下,您应该首先简单地检索categories
。 然后使用关系属性访问检索相关数据。
例如
$categories = Category::query()
->with('products')
->where('slug', request('category'))
->get();
$products = $categories->flatMap->products;
$pivots = $products->map->pivot;
使用 whereHas 解决了两次:
$products = Product::with('categories')->whereHas('categories',function($query){
$query->where('slug',request()->category);
})->whereHas('orders',function($query){
$query->where('orders.user_id',Auth::id());
})->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.