亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Eloquent Laravel 從多個表中獲取數據

Eloquent Laravel 從多個表中獲取數據

PHP
MMTTMM 2022-12-30 17:04:10
我花了兩天時間試圖解決這個問題,但我不知道如何解決。我有五張桌子產品類別類別_產品命令訂單_產品從視圖中,單擊類別按鈕我必須獲取他訂購的所有具有相關類別的產品。我有當前的模型:產品型號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。
查看完整描述

2 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊


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


查看完整回答
反對 回復 2022-12-30
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

基本上 Eloquent 模型不鼓勵連接表來檢索數據。它應該僅用于過濾結果(因此您需要使用刪除其他表的字段->select('original_table.*'))


在這種情況下,您應該首先簡單地檢索categories。然后使用關系屬性訪問檢索相關數據。


例如


$categories = Category::query()

    ->with('products')

    ->where('slug', request('category'))

    ->get();

$products = $categories->flatMap->products;

$pivots = $products->map->pivot;


查看完整回答
反對 回復 2022-12-30
  • 2 回答
  • 0 關注
  • 122 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號