簡體   English   中英

在 eloquent 查詢中獲取模型的 ID

[英]Get ID of model inside eloquent query

有沒有辦法在查詢中獲取 ID?

我不知道如何流利地解釋這一點,但我正在嘗試獲取每個產品的產品選項,但我需要使用 with 語句中的產品 ID 來做到這一點。

類似的東西,但$idOfModel顯然應該是每個產品的 id。

$products = Product::with('attributes', function($q) {
            $q->with('product_options', function($q) {
                $q->where('product_id', $idOfModel)->with('variable', function($q) {
                    $q->where('product_id', $idOfModel);
                });
            })->groupBy('id');
        })->take(10)->get();

目標是為每種產品選擇其變量/值

所以基本上你只需要正確定義關系,雄辯就會為你做所有事情(即使是嵌套的急切加載

// Product model
// relations that fits your schema
public function attributes(){  
  return $this->relationName(Attribute::class); 
}

public function productOptions(){
  return $this->relationName(ProductOption::class);
}

//ProductOption model
public function vaiable(){
  return $this->relationName(Variable::class);
}

// then in controller
$products = Product::with(['attributes', productOptions.variable'])
  ->take(10)
  ->get();

您可以使用您的第一個Builder訪問您的productId ,如下所示。

$products = Product::with('attributes', function($q1) {
        $q1->with('product_options', function($q2) use ($q1) {
            $q2->where('product_id', $q1->id)->with('variable', function($q3) use ($q1) {
                $q3->where('product_id', $q1->id);
            });
        })->groupBy('id');
    })->take(10)->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM