Laravel get Eloquent relation by same name as its attribute

后端 未结 3 1418
攒了一身酷
攒了一身酷 2021-01-18 11:44

I have database tables like this:

shoot: id, name, programme
programme: id, name

The eloquent relationship in the shoot is defined like thi

3条回答
  •  梦谈多话
    2021-01-18 12:29

    You shouldn't use the same name for the both relationship and column name, else you'll receive always the column name so try to edit one of them, I think the easiest one here is the relationship name :

    public function programmeObj() {
        return $this->belongsTo('App\Programme', 'programme', 'id');
    }
    

    Then call it as :

    echo $shoot->programmeObj;
    

    NOTE : But if you want to follow conventions you should replace the name attribute by programme_id so :

    public function programme() {
        return $this->belongsTo('App\Programme', 'programme_id', 'id');
    }
    

    Hope this helps.

提交回复
热议问题