Eloquent 嵌套关系在使用 SELECT 语句时返回 null
Eloquent Nested Relationship Returning null while using SELECT statement
我将 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();
我怎样才能得到一个 Package
模型及其 Task
和 Task's
发布者(这是一个 User
模型,而只有 Task
的特定列和 User
被返回?
谢谢。
OP 的解决方案。
我猜想选择 Task
的特定列会导致 Task.published_by
到 null
,因此 publisher()
无法查询 User
。解决方法如下图:
// This works well
Package::with('task:id,title,published_by', 'task.publisher:id,nick')->get()
我将 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();
我怎样才能得到一个 Package
模型及其 Task
和 Task's
发布者(这是一个 User
模型,而只有 Task
的特定列和 User
被返回?
谢谢。
OP 的解决方案。
我猜想选择 Task
的特定列会导致 Task.published_by
到 null
,因此 publisher()
无法查询 User
。解决方法如下图:
// This works well
Package::with('task:id,title,published_by', 'task.publisher:id,nick')->get()