【发布时间】:2016-08-27 15:20:19
【问题描述】:
我一直在关注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
它返回所有 Sections。同样,当我尝试update 时,它会更新所有部分:
$topic->section()->update([
'content' => $input['section']
]); // updates many
我如何将它发送给update 仅最新的/预期的?
【问题讨论】:
-
因为你使用的是查询方法而不是关系指针。它应该是 $topic->section->name 或所需的部分属性。更新 $topic->section->save(['foo'=>'bar']) 相同
-
文章中描述的解决方案有一些陷阱。你找到了其中之一。
标签: php laravel eloquent laravel-5.2 relationship