【问题标题】:Laravel Eloquent belongsToManyLaravel Eloquent 属于ToMany
【发布时间】:2019-07-27 05:15:14
【问题描述】:

我有三个数据库表:

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

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

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

当用户访问个人资料站点时,我想从表中加载所有属性,但我还想从中间表 (pivot) 中为该用户 (id) 加载内容。

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

在配置文件模型中使用此类,我将无法获得所有属性。

当我在属性模型中使用 Profiles() 类时,我得到了每个属性,但不是用户的内容……而是每个用户的内容。

【问题讨论】:

  • 不知道你在用那个belongsToMany()做什么;它最多有 4 个属性:belongsToMany('Model', 'table', 'local_key', 'foreign_key');: "第三个参数是您定义关系的模型的外键名称,而第四个参数是您所在模型的外键名称加入:"

标签: php laravel eloquent relationship


【解决方案1】:

当您使用Many-to-many relationship 时,您可以使用pivot 属性访问中间表。我看到你在关系中已经有了withPivot 指令,所以你准备好了。

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

【讨论】:

    猜你喜欢
    • 2017-10-27
    • 1970-01-01
    • 2020-08-10
    • 2015-01-10
    • 2021-08-25
    • 2018-07-17
    • 2020-04-25
    • 2014-07-19
    • 2023-03-28
    相关资源
    最近更新 更多