php - 在 Laravel Eloquent 中使用 “With()” 函数获取特定列

标签 php laravel orm eloquent laravel-query-builder

我有两个表,UserPost。一个User可以有很多posts,一个post只属于一个user

在我的 User 模型中,我有一个 hasMany 关系...

public function post(){
    return $this->hasmany('post');
}

在我的 post 模型中,我有一个 belongsTo 关系...

public function user(){
    return $this->belongsTo('user');
}

现在我想使用 Eloquent with() 连接这两个表,但需要第二个表中的特定列。我知道我可以使用查询生成器,但我不想。

当我在 Post 模型中写...

public function getAllPosts() {
    return Post::with('user')->get();
}

它运行以下查询...

select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)

但我想要的是……

select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)

当我使用...

Post::with('user')->get(array('columns'....));

它只返回第一个表中的列。我想要使​​用第二个表中的 with() 的特定列。我该怎么做?

最佳答案

好吧,我找到了解决方案。它可以通过在 with() 中传递一个 closure 函数作为数组的第二个索引来完成,例如

Post::query()
    ->with(['user' => function ($query) {
        $query->select('id', 'username');
    }])
    ->get()

它只会从其他表中选择 idusername。我希望这对其他人有帮助。


请记住,主键(在本例中为 id)需要是第一个参数 $query->select() 来实际检索必要的结果。*

关于php - 在 Laravel Eloquent 中使用 “With()” 函数获取特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19852927/

相关文章:

PHP, mysqli 数组

php - 从SQL中的文本字段中提取单词

PHP - 复制导致 HTTP 错误 500

c# - 我可以传入 T.Property 吗?另外,改进这种方法的想法?

php - 我如何在 PHPSpec 中处理 Doctrine QueryBuilder?

mysql - 使用 laravel 6 显示 Blob 列中的文档

php - 我可以在 Laravel 5 session 中保存对象、对象集合吗?

php - 我如何将一小部分 zend 框架包含到 laravel 中?

python - SQLAlchemy 使用现有主键创建新对象

mysql - sails.js 查询表列内的 json 对象