【问题标题】:Select specific column only from Laravel 5.2 Relation query not working [duplicate]仅从 Laravel 5.2 关系查询中选择特定列不起作用 [重复]
【发布时间】:2020-09-05 10:29:31
【问题描述】:

所以我有一个查询,我只想获取关系中的特定列但不工作。顺便说一句,我正在使用 Laravel 5.2。这是我所拥有的:

$job = Job::query()->whereId($job_id)
        ->with([
            'jobType' => function (Relation $query) {
                $query->select(['name']);
            },

        ])
    ->first();

如果我这样做,jobType 关系将返回null,如下所示:

如果我删除$query->select(['name']);,它会包含job_type 表中的数据。如何才能成功地从表中获取特定列?

【问题讨论】:

  • @Remul 尝试过,但结果相同。
  • 你真的读了吗?你必须包含链接jobs和jobType的列,否则你怎么知道哪个job和jobType属于一起,因此eloquent返回null。
  • 您还需要选择主键和/或外键

标签: php laravel laravel-relations


【解决方案1】:

也许这可以..要获取特定列,您需要特定的jobtype

$job = Job::query()->whereId($job_id)
        ->with(['jobType' => function ($q) use($jobType) {
                $q->where(// check the condition on jobtype table);
                $q->select(['name']);
            },
        ])
    ->first();

【讨论】:

  • 我认为 where 子句是不必要的,我通过在 select 子句中包含 id 列让它起作用。
猜你喜欢
  • 1970-01-01
  • 2016-07-25
  • 2021-12-24
  • 2021-03-12
  • 1970-01-01
  • 2011-06-28
  • 2017-04-23
  • 1970-01-01
  • 2019-09-28
相关资源
最近更新 更多