【问题标题】:Laravel select specific columns with Eloquent while eager loadingLaravel 在急切加载时使用 Eloquent 选择特定列
【发布时间】:2021-01-21 16:43:19
【问题描述】:

我正在使用 Laravel 8。我有 2 个表并尝试使用 Eloquent 从两个表中选择特定列:

$ids = [1, 8, 14];
$food = Food::with(
            ['animals' => function ($query)
            {
                $query->select('id', 'name');
                $query->where('status', 1);
            }])
            ->select('id', 'type')
            ->whereIn('id', $ids)
            ->where('status', 1)
            ->get();

但是,如果我向 Food 模型添加 select 方法,Laravel 会为 animals 表返回 null

如果我没有在 Food 模型上指定选择,Laravel 会从 Food 模型和 idname 中返回 animals 表中的所有内容。

如何在使用 Eager Loading 时同时从 FoodAnimal 表中进行选择?

【问题讨论】:

  • 您必须确保还选择了关系所需的任何外键
  • 可以分享animals关系函数吗?
  • @lagbox 这就是问题所在,非常感谢您指出。我从选择查询中遗漏了一个外键!如果您创建一个答案,我会批准它!
  • 在这种情况下哪个表有外键,顺便说一句?
  • @lagbox animals 表。我将它添加到food 表的选择中,它立即生效。

标签: laravel eloquent


【解决方案1】:

您必须确保从关系的任一方选择该 ID 的关系所需的任何外键。这允许 Eloquent 将父母与他们的孩子进行匹配。

【讨论】:

    【解决方案2】:

    试试这个,在select中指定表。

    Food::with(['animals' => function ($query) {
                $query->where('status', 1);
            }])
            ->select('food.id', 'animals.type', 'food.type')
            ->whereIn('id', $ids)
            ->where('status', 1)
            ->get();
    

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2021-10-02
      • 2021-10-02
      • 2020-01-13
      • 2014-11-12
      • 1970-01-01
      相关资源
      最近更新 更多