【问题标题】:how attach the relationship when getting data from database by model in laravel在laravel中按模型从数据库中获取数据时如何附加关系
【发布时间】:2021-09-21 21:10:49
【问题描述】:

我想在 laravel 中按模型从数据库中获取数据时附加关系。 我使用这些代码来做到这一点。 但我知道有更好的方法来做到这一点。

感谢您的帮助。

$courses = Cource::orderBy('id' , 'desc')->take($count)->get();
 foreach($courses as $cource){
        $cource['image'] =  $cource->image()->get();
        $cource['rate'] = $cource->rate()->get();
}

【问题讨论】:

  • docs 可能是寻找此类问题的第一个地方。 Laravel 有 ton 的内置功能。因此,如果您认为应该有更好的方法来完成某事,请首先查看文档;可能已经有一种内置方式(例如急切加载)。
  • 感谢您的指导。我阅读了文档,并且我了解 with () 不适用于 morph 关系

标签: laravel eloquent relationship


【解决方案1】:

您可能想使用with

$courses = Cource::orderBy('id' , 'desc')
    ->take($count)
    ->with(['image', 'rate'])
    ->get();

【讨论】:

  • 我忘了说我稍后使用它但不工作并给我空数组。
  • give me the empty array 这种情况何时发生?当你序列化它们时?当您尝试访问它们时?还是什么?..
  • 我认为这不起作用,因为我使用了变形关系,我想用 with( ) 来做这个。
  • 在模型类上尝试protected $with = ['image', 'rate'];
【解决方案2】:
$courses = Cource::orderBy('id' , 'desc')
->take($count)
->with(['image', 'rate'])
->get();

条件是使用除morph relationship之外的所有关系

【讨论】:

    猜你喜欢
    • 2020-08-17
    • 2018-10-24
    • 2016-03-09
    • 2021-07-17
    • 2019-09-12
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多