Eloquent Laravel 从多个表中获取数据

我花了两天时间试图解决这个问题,但我不知道如何解决。

我有五张桌子

  • 产品

  • 类别

  • 类别_产品

  • 命令

  • 订单_产品

从视图中,单击类别按钮我必须获取他订购的所有具有相关类别的产品。

我有当前的模型:

产品型号


class Product extends Model

{

    public function categories() {

        return $this->belongsToMany('App\Category');

    }


    public function orders() {

        return $this->belongsTo('App\Order');

    }

}

品类模型


public function products() {

    return $this->belongsToMany('App\Product');

}

订货型号


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。



MMTTMM
浏览 98回答 2
2回答

LEATH

使用 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();

杨魅力

基本上 Eloquent 模型不鼓励连接表来检索数据。它应该仅用于过滤结果(因此您需要使用删除其他表的字段->select('original_table.*'))在这种情况下,您应该首先简单地检索categories。然后使用关系属性访问检索相关数据。例如$categories = Category::query()    ->with('products')    ->where('slug', request('category'))    ->get();$products = $categories->flatMap->products;$pivots = $products->map->pivot;
打开App,查看更多内容
随时随地看视频慕课网APP