I’m training with many to many relationships and today i’m trying to compare 2 pivot tables.
I’m trying a site for a nutritionist.
On one hand the nutritionist/admin can create patient’s card (my table "User". In this cards he informs the regime’s type of this patient. It’s a many to many relationship so i made a "regime_user" table pivot.
Schema::create('regime_user', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('regime_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
On the other hand he can create receipts (my table is "Recette") and informs regime’s type. Again i use a pivot table "recette_regime".
Schema::create('recette_regime', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->foreignId('recette_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('regime_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
});
Of course in my Models i’ve added the relation:
For the User Model :
public function regimes()
{
return $this->belongsToMany(Regime::class);
}
For the Regime Model :
public function users()
{
return $this->belongsToMany(User::class);
}
What i want to do now in the receipts’s index is to display for the auth()->user() only the receipts who has the same regime’s types. So i need to compare the 2 pivots table :
- which regime’s types has the auth()->user()
- find the receipts which have the same regime’s types
I’ve read the doc and find nothing i could use. Can you help me please?
2
Answers
I’m not sure what kind of data you have inside of
"Regime & Recette"
but I will assume in this example that the columnname
exists, to show the concept of how you can present the data.User Model:
Regime Model:
Recette Model:
In UserController show function:
In sampleView Blade:
You can get it by using
whereHas()