我有Tag
和Attendee
Eloquent 模型,它们是多对多的关系。数据透视表还有另外两个属性 -value_int
和value_string
. 我的Attendee
模型看起来像这样:
class Attendee extends Model
{
public $timestamps = false;
protected $fillable = [
'event_id'
];
public function tags() {
return $this->belongsToMany('App\Models\Tag', 'attendee_tag', 'attendee_id', 'tag_id')
->withPivot(['value_string', 'value_int']);
}
public function scoreTagValue($tag_id) {
return $this->tags->where('tag_id', '=', $tag_id)->first();
}
}
我想要的是根据Attendee
模型和变量获取枢轴值tag_id
,所以我写了scoreTagValue
函数,但它总是返回null
,我不知道为什么:( 我这样称呼它: $attendee->scoreTagValue($tag_id)
。谢谢你的帮助 :)
您需要访问关系,而不是属性:
public function scoreTagValue($tag_id) {
return $this->tags()->where('tag_id', '=', $tag_id)->first();
}
此外,根据 docs,withPivot()
不接受数组,因此:
->withPivot('value_string', 'value_int');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句