Home > Blockchain >  Laravel nested relationship automatically to model
Laravel nested relationship automatically to model

Time:12-04

I wonder if I can do dynamic relationship from pivot table. I'm using mariadb and I have structure tables like this below

table user_has_profiles as pivot model App\Models\PivotProfile

user_id profile_id profile_type
uuid-1 uuid-up App\Models\UserProfile
uuid-1 uuid-tp App\Models\TeacherProfile

table user_profiles as model App\Models\UserProfile

id gender birthday
uuid-up male 2022-01-01

table teacher_profilesas model App\Models\TeacherProfile

id teacher_number country
uuid-tp TC-001 France

if I query with model Pivotprofile::get() how can I get result like this

[
 0 => [
   "user_id" => "uuid-1",
   "profile_id" => "uuid-up",
   "profile_type" => "App\Models\UserProfile",
   "profile" => [
           "id" => "uuid-up",
           "gender" => "male",
           "birthday" => "2022-01-01"
   ]
 ],
 1 => [
   "user_id" => "uuid-1",
   "profile_id" => "uuid-tp",
   "profile_type" => "App\Models\TeacherProfile",
   "profile" => [
           "id" => "uuid-tp",
           "teacher_number" => "TC-001",
           "country" => "France"
   ]
 ],
]

So PivotProfile automatically have relation according to profile_type. Or maybe you have better option in structure table if users have multiple profile table. Thank you

CodePudding user response:

One option to achieve this would be to create a polymorphic relationship in the PivotProfile model.

First, define the relationship in the PivotProfile model:

public function profile()
{
    return $this->morphTo();
}

Then, you can use the morphTo() method in your query to retrieve the related profile model:

$profiles = PivotProfile::with('profile')->get();

This will return a collection of PivotProfile objects with a "profile" property that contains the related profile model, according to the "profile_type" field in the pivot table.

You can then iterate over the collection and access the profile data for each pivot profile:

foreach ($profiles as $profile) {
    $profileData = $profile->profile;

    // access profile data here, e.g. $profileData->gender
}

Note that this solution assumes that you have defined the correct morph classes in the profile_type field of the pivot table. For example, if the profile_type is "App\Models\UserProfile", then the UserProfile model should have a $morphClass property set to "App\Models\UserProfile".

Hope this helps! Let me know if you have any further questions.

  • Related