首页 > 解决方案 > 如何在 eloquent 的子查询函数中使用“Select()”

问题描述

我可能没有使用正确的措辞,但我的问题是:

我有这个查询

$result = Table_one_model::with(['Table_two' => function($query) use ($thing_id) {
    $query->where('thing_id', $thing_id);
}])
->select('col_one', 'col_two')
->get();

我想从 table_two 的选择中再添加一件事,但是如果我将它添加到上面的现有选择中,就像select('col_one', 'col_two', 'col_from_other_table')它不起作用一样,并且如果我将选择添加到下面的 table_two 查询中,它也不起作用:

$result = Table_one_model::with(['Table_two' => function($query) use ($thing_id) {
    $query->where('thing_id', $thing_id)->select('col_from_other_table');
}])
->select('col_one', 'col_two')
->get();

在这两种情况下,我都会得到结果,但结果table_two只是显示为“null”

没有第二个表选择我得到这个结果:

{
  "col_one": 0,
  "col_two": 0,
  "table_one": {
    "id":1,
    "blah":0,
    "col_from_other_table":0
    ...all the contents of table two
  }
}

通过 table_two 查询中的选择,我得到了这个:

{
  "col_one": 0,
  "col_two": 0,
  "table_one": {
    null
  }
}

选择与其他选择列在同一位置,它完全中断并说该列不存在。

我认为这只是通过某种方式以某种方式到达该列的问题table_one.col_from_other_tableortable_one->col_from_other_table但我不能在选择中使用其中任何一个

有任何想法吗?

标签: laraveleloquent

解决方案


您还需要根据关系选择 id 或外部 id。这就是为什么它抛出空值。例如,想象两个模型。

Parent: id (pk), name, phone, email
Child:  id (pk), name, phone, email, parent_id (fk)

想象一下,我们只需要获取名称。在 Eloquent 中看起来像这样:

$children = Child::select('children.name'. 'children.parent_id') /* Need to select children.parent_id */
->with(['parent' => function ($query) {
    $query->select('parents.id', 'parents.name');                /* Need to select parents.id */
}])
->get();

$parents = Parent::select('parents.id', 'parents.name')    /* Need to select parents.id */
->with(['children' => function ($query) {
    $query->select('children.name', 'children.parent_id'); /* Need to select children.parent_id */
}])
->get();

推荐阅读