我正在尝试在 Laravel 中使用 Eloquent 来运行查询。我正在使用 with()
函数来从关系中获取结果,但是这总是返回 null
。
这是我的代码:
Posts::query()
->select('id')
->with([
'author:id',
'category.images:url',
]);
使用 getQueryLog()
函数转储查询,如果我在具有相同绑定(bind)的 SQL 客户端内部运行查询,我会得到返回结果,但是响应看起来像这样...
{
id: 1,
category: {
id: 1,
category_images: null
}
}
我已经尝试用谷歌搜索这个问题,但找不到任何关于它的信息。
提前致谢。
最佳答案
像这样使用您的查询:
Posts::query()->select('id')->with([ 'author', 'category' ])->get();
在 Posts 模型中
public function author()
{
return $this->belongsTo('Authors::class', 'author_id', 'id')->select('id');
}
public function category()
{
return $this->belongsTo('Categories::class', 'category_id', 'id')->select('id', 'images.id', 'images.url');
}
关于php - Eloquent |使用 with() 导致返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51320418/