简体   繁体   中英

Laravel Eloquent belongsToMany

I have three db tables:

attributes
---------------------------------
| id | name | showed_name | class

attributes_profiles
----------------------------------------------
| id | attribute_name | profile_id | content |

profiles
------------
| id | ... |

When a User go on the profile site, I want to load ALL Attributes from the table, but I also want the content from the intermediate table (pivot) for this user (id).

public function Attribute(){
  return $this->belongstoMany('App\Attribute', 'attributes_profiles', 'profile_id', 'attribute_name','id','name')->withPivot('content');
}

With this class in the profiles model, I wouldn't be able to get all attributes.

When I use a Profiles() Class in the Attributes Model, I get every Attribute but not the content for the user... but for every user.

When you use a Many-to-many relationship , you can access the intermediate table with the pivot attribute. I see you already have the withPivot directive in the relationship, so you are ready to go.

foreach($profile->attribute as $attribute) {
  $attribute->pivot->content; // The content in the intermediate table
}

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