【问题标题】:Eloquent Nested Relationship Returning null while using SELECT statement雄辩的嵌套关系在使用 SELECT 语句时返回 null
【发布时间】:2018-03-15 10:58:19
【问题描述】:

我将 Slim 与 Eloquent 结合使用,并且遇到了一些问题,即嵌套关系在选择特定列时返回 null。
我的代码如下所示:

class User extends Model {}
class Task extends Model {
    public function publisher() {
        return $this->belongsTo('App\User', 'published_by');
    }
}
class Package extends Model {
    public function task() {
        return $this->belongsTo('App\Task', 'task_id');
    }
}

奇怪的事情发生了:

// Works well, I got publisher info and task info, but some columns are useless
// I just want to hide them and (may) improve performance in this case
Package::with('task.publisher:id,nick')->get();
// I got a null publisher
Package::with('task:id,title', 'task.publisher:id,nick')->get();

// Error: Unknown column `publisher`
Package::with('task:id,title,publisher')->get();
Package::with('task:id,title,publisher:id')->get();

如何获得带有 TaskTask's 发布者的 Package 模型(这是 User 模型,而仅返回 TaskUser 的特定列?
谢谢。

【问题讨论】:

  • 您可以回答自己的问题。将帖子中受人尊敬的部分放在答案部分。而不是接受它作为答案。
  • 我将您的解决方案移至社区 wiki 答案。
  • 非常感谢,由于某些原因我这几天没有查看通知,现在我知道了诀窍。

标签: php laravel eloquent lumen


【解决方案1】:

OP 的解决方案。

我猜想选择Task的具体列会导致Task.published_by变成null,所以publisher()不能查询到User。解决方法如下图:

// This works well
Package::with('task:id,title,published_by', 'task.publisher:id,nick')->get()

【讨论】:

    猜你喜欢
    • 2016-09-18
    • 2017-10-18
    • 1970-01-01
    • 2017-07-29
    • 2014-10-23
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多