Relation belongsToMany

Par agencep, il y a 3 ans


Bonjour,

J'ai besoin d'extraire les informations en relation d'une table pivot (country_id et label_id). Comment faire svp ?

Table #1 (Bes) id, dateday, total, etc ... Table #2 (Products) id, title, etc ... Table #3 (bes_product) => Pivot bes_id, product_id, country_id, label_id, total, etc ... **Model Product.php** public function products(){ return $this->belongsToMany(Product::class) ->withPivot(['country_id', 'label_id', 'total']); } **Model Bes.php** public function Bes() { return $this->belongsToMany(Bes::class); }

Ce que je veux

Je veux obtenir la relation country_id et label_id qui se trouve dans bes_product

Ce que j'obtiens

Bes::where('id', $request->query('id')) ->orderBy('dateday', 'desc') ->with(['products']) ->first(); "id" => 2 "dateday" => "2022-11-30" "total" => "900.00" "is_locked" => 0 "is_warning" => 0 "created_at" => "2022-11-30T18:50:55.000000Z" "updated_at" => "2022-11-30T18:50:55.000000Z" "products" => array:2 [▼ 0 => array:12 [▼ "id" => 1 "title" => "test" "family_id" => 3 "provider_id" => 1 "country_id" => 205 "tax_id" => 2 "unit_id" => 1 "is_active" => 1 "created_at" => "2022-11-28T15:10:35.000000Z" "updated_at" => "2022-11-28T15:10:35.000000Z" "deleted_at" => null "pivot" => array:5 [▼ "bes_id" => 2 "product_id" => 1 "country_id" => 3 "label_id" => 1 "price" => "1.00" ] ] ] ]

2 réponses

agencep, il y a 3 ans

ben justement je cherche ou inserer cette relation de lanel_id pour que j´obtiens les infos de la table lanels

Grafikart, il y a 3 ans

Comme tu le vois tu as l'info dans les données normalement tu peux récupérer ça via ton model

$product->pivot->label_id