簡體   English   中英

在Laravel中檢索數據透視表的列值

[英]Retrieve Pivot table column value in Laravel

我遇到了一個不應該發生的奇怪問題。

我有一段代碼來檢索數據透視表的值

$product = Product::find(296);

dd($product->pivot->aisle);

正如我在其他幾個項目中所做的那樣,它應該可以工作。 今天突然給我以下錯誤:

(1/1) ErrorException
Trying to get property of non-object
in ProductController.php (line 42)
at HandleExceptions->handleError(8, 'Trying to get property of non-object', 
'C:\\laragon\\www\\Sales\\app\\Http\\Controllers\\ProductController.php', 
42, array('retailer' => object(Retailer), 'product' => object(Product)))
in ProductController.php (line 42)

在我的產品模型中,我有以下內容:

public function retailers(){

return $this->belongsToMany(Retailer::class)->withPivot('aisle','ifinstock','ifstock','ifticketed','ifonshelf','iflowstock','note','id','created_at','updated_at','stocklevel');

}

在我的零售商模型中,我有:

public function products(){

return $this->belongsToMany(Product::class)->withPivot('aisle','ifinstock','ifstock','ifticketed','ifonshelf','iflowstock','note','id','created_at','updated_at','stocklevel');

}

我只是看不到哪里出了問題?

當您訪問Product::find(296)您沒有通過相關模型進行訪問,而是在訪問Product模型本身,因此Laravel / Eloquent不會加載任何關系信息,例如樞軸字段,因為這些樞軸字段不是沒有為產品模型定義,而是為關系定義的。

如果要這樣做:

$retailer = Retailer::with('products')->find(...);

然后訪問該模型上的“產品”關系,它應該可以工作:

$product = $retailer->products->first();
var_dump($product->pivot);

總之,產品本身沒有任何樞軸字段。 關鍵字段用於產品零售商之間的關系。

暫無
暫無

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

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