在 Eloquent 中获取和更新最新的相关模型

Getting and updating the latest related model in Eloquent

我一直在关注 this article 并为自己设置了这些模型:

class Topic extends Node{
    public function section(){
        return $this->hasOne('App\Section')->latest();
    }
    public function allSections(){
        return $this->hasMany('App\Section');
    }
}
class Section extends Model
{
    public function topic(){
        return $this->belongsTo('App\Topic');
    }
}

当我使用预先加载查询数据时,结果符合预期,即对于每个 Topic,只有一个 Section返回(最新)。

Topic::with('section')
   ->where('id', $id)
   ->get(); //returns one section for each topic

然而,当我这样查询时:

$section = $topic->section()->get(); //returns many

它 returns 所有 部分 。同样,当我尝试 update 时,它会更新所有部分:

$topic->section()->update([
   'content'   => $input['section']
]); // updates many

我如何才能将它发送到 update 只有 latest/intended 一个?

你做错了。试试这个:

$topic->section->update([
   'content'   => $input['section']
]);