【问题标题】:Equivalent for App\Model::with('relation') in Laravel 7.x controller等效于 Laravel 7.x 控制器中的 App\Model::with('relation')
【发布时间】:2020-11-28 03:11:11
【问题描述】:

在我的控制器中,我返回一个 json 对象:

  public function show(Comic $comic)
  {
    //
    return Comic::with('series')->findOrFail($comic->comic_id);
  }

是否有更短的形式来获得相同的输出?我在想

  public function show(Comic $comic)
  {
    //
    return $comic->with('series');
  }

但这不起作用并引发错误:

TypeError: Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given

谢谢。

【问题讨论】:

    标签: php laravel eloquent laravel-7


    【解决方案1】:

    当然,有“Lazy Eager Loading”这样的东西:

    $comic->load('series');
    

    这会在您已经拥有的模型实例上为您加载该关系,因此您不必再次查询该模型。 load 返回模型实例,因此您可以将调用结果作为模型实例返回。

    Laravel 7.x Docs - Eloquent - Relationships - Eager Loading - Lazy Eager Loadingload

    【讨论】:

    • 谢谢(也很抱歉)。我应该更仔细地阅读文档中的那一章。
    猜你喜欢
    • 2020-05-19
    • 2018-04-06
    • 2015-12-31
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多