Laravel get Eloquent relation by same name as its attribute

后端 未结 3 1363
攒了一身酷
攒了一身酷 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:41

    This will returns always the column in your database if it exists, that's ID 1.

    When you call dump($shoot); you should get the array with all attributes. But when you run the following you should get the name:

    Your model:

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

    And your controller:

    $shoot = Shoot:where('id','=',1)->first();
    return $shoot->programmeData->name; // returns name
    

    Hope this works!

提交回复
热议问题