duanchi1230 2017-08-17 09:35
浏览 101
已采纳

Laravel 5 - 基于模型和相关的模型ID获得特定的多对多关系

I've got Tag and Attendee Eloquent models, they are in many-to-many relation. Pivot table has also two more attributes – value_int and value_string. My Attendee model looks like this:

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();
    }

}

What I want is to obtain pivot values based on Attendee model and variable tag_id, so I've written scoreTagValue function, but it always returns null and I don't know why :( I'm calling it this way: $attendee->scoreTagValue($tag_id). Thanks for your help :)

  • 写回答

1条回答 默认 最新

  • dqsot35145 2017-08-17 09:44
    关注

    You need to access the relation, not the property:

    public function scoreTagValue($tag_id) {
        return $this->tags()->where('tag_id', '=', $tag_id)->first();
    }
    

    Also, according to the docs, withPivot() does not take an array, so:

    ->withPivot('value_string', 'value_int');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真