[英]Laravel Eloquent belongsToMany
我有三個數據庫表:
attributes
---------------------------------
| id | name | showed_name | class
attributes_profiles
----------------------------------------------
| id | attribute_name | profile_id | content |
profiles
------------
| id | ... |
當用戶訪問個人資料站點時,我想從表中加載所有屬性,但是我也希望該用戶(id)從中間表(數據透視表)中加載內容。
public function Attribute(){
return $this->belongstoMany('App\Attribute', 'attributes_profiles', 'profile_id', 'attribute_name','id','name')->withPivot('content');
}
有了Profiles模型中的此類,我將無法獲得所有屬性。
當我在屬性模型中使用Profiles()類時,將獲得每個屬性,而不是用戶的內容...而是每個用戶。
使用多對多關系時 ,可以使用pivot
表屬性訪問中間表。 我看到您在關系中已經有了withPivot
指令,因此您可以開始使用。
foreach($profile->attribute as $attribute) {
$attribute->pivot->content; // The content in the intermediate table
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.