简体   繁体   中英

Retrieve Pivot table column value in Laravel

I'm having a strange issue that shouldn't happen.

I have a piece of code to retrive value of a pivot table

$product = Product::find(296);

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

It should work as I've done this for a few other projects. Suddenly it's giving me the following error today:

(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)

In my product model I have below:

public function retailers(){

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

}

In my retailer model I have :

public function products(){

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

}

I just can't see where went wrong?

When you access Product::find(296) you're not accessing through a related model, you're accessing the Product model itself, therefore Laravel/Eloquent would not have loaded any relationship information such as the pivot fields because those pivot fields aren't defined for the Product model, they are defined for the relationship.

If you were to do:

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

Then access the Products relationship on that model, it should work:

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

In summary, Products itself doesn't have any pivot fields. The pivot fields are for the relationship of Products and Retailers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM