【问题标题】:Getting and updating the latest related model in Eloquent在 Eloquent 中获取和更新最新的相关模型
【发布时间】: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


【解决方案1】:

你做错了。试试这个:

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

【讨论】:

  • 您没有提供任何关于如何解决问题的说明。
  • 这不是问题。他使用关系 'hasOne' 就像 'belongsToMany'。
  • 错了。你应该已经说明了他是用关系查询的方法,而不是用相关对象指针,然后你把代码解决了。这对他来说是个问题,因为他不理解这个概念。这将改善您未来的答案。
  • 好的。我会。谢谢。
猜你喜欢
  • 2013-11-22
  • 2016-08-28
  • 2017-09-21
  • 2015-10-23
  • 2019-10-10
  • 2021-03-20
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多