如何在急切加载中使用 DB::raw

时间:2021-01-11 06:42:40

标签: php mysql laravel

我目前在 laravel 中使用预先加载并使用了 select() 方法。但是,当我尝试选择子表时,它返回错误。请看下面我的代码。

控制器

$posts = Post::with('author');

$posts->select(['body', DB::raw('CONCAT(users.first_name, " ", users.last_name) as AUTHOR')]);

上面的代码返回这个错误:

<块引用>

未找到列:“字段列表”中的 1054 列“users.first_name”未知

所以我试着让它变成这样:

$posts = Post::with('author');

$posts->select(['body', DB::raw('CONCAT(author.first_name, " ", author.last_name) as AUTHOR')]);

现在我使用关系来获取名字和姓氏,但我遇到了同样的错误。有什么想法吗?

更新

我正在为这个项目使用 laravel 5.2

1 个答案:

答案 0 :(得分:0)

你应该能够解决这个问题:

$posts = Post::with('author:id,first_name,last_name')->get();

基于laravel docs,您必须提供关系表的列名,如上。不要忘记添加“id”,否则它将无法正常工作。