【问题标题】:Laravel Eloquent ->with() and ->select() conflict with each otherLaravel Eloquent ->with() 和 ->select() 相互冲突
【发布时间】:2014-12-30 09:10:58
【问题描述】:

考虑这段代码:

Articles
::select('article_id', 'article_text')  //This one does not work as expected
->with([
    'user' => function($q){
        $q->select('user_id', 'user_name'); // This one works fine
    }
])
->get();

在 Eloquent 中构建查询时,我们可以使用 ->with() 来检索关联的模型。我们还可以附加 ->select() 来确定应该从关联模型中选择哪些列。但是,看起来我们失去了指定应该从我们查询的基本模型中选择哪些列的可能性。

在本例中,由于第一个::select,返回的最终结果不包括user,因为它不包括在::select 列表中。如果我在其中包含它,那么它会引发关于 column not found 的错误。 Eloquent 不够聪明,无法理解我的意思是关系,而不是列。

是否可以指定应该从userarticle 返回哪些列?

【问题讨论】:

  • 你的假设有点错误。第一个select 中没有user 并不重要。这些是 2 个单独的查询,所以你选择什么并不重要,只要你包括所有涉及的键(PK、FK)——就像@lagbox 已经说过的那样。

标签: laravel laravel-4 eloquent


【解决方案1】:

您可以使用预先加载约束选择所需的列,但您仍然需要至少选择用于关系的列。

随机示例:

User::with(['tickets' => function ($q) {
    $q->select('user_id');
}])->select('id')->get();

这些是返回关系结果并将它们附加到正确模型所需的最少字段。

您至少需要从tickets 中选择user_id 和从users 中选择id。这些是用于此关系的列。 tickets.user_id -> users.id

查询日志:

'select `id` from `users`'

'select `user_id` from `tickets` where `tickets`.`user_id` in ( .... )'

拥有这些字段可为您提供关系返回结果所需的内容,现在您可以向这些选择添加其他字段。

希望对你有帮助。

【讨论】:

  • 知道为什么这个代码:$orders = OrderHeader ::where('created_by', $this->user->id) ->with(['status' => function ($q) { $q->select('id','name'); }]) ->select('id') ->get();返回 nginx 502 错误。如果我删除 'select' 或 'with' 效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 2020-06-29
  • 1970-01-01
相关资源
最近更新 更多