php - Laravel hasMany 关系选择特定列问题

标签 php mysql laravel has-many eloquent-relationship

我在我的 laravel 模型中有一个关系

/**
 * Relation with calculations table
 *
 * @return object
 */
public function calculations()
{
    return $this->hasMany('App\Calculation');
}

当我选择关系为的数据时

$this->diamonds
->select('id', 'image', 'number', 'weight', 'diamond_date', 'price')
->with('calculations')->first();

它返回所有数据并且工作正常,但是当我想选择特定列时它返回 [] 空白数组

$this->diamonds
->select('id', 'image', 'number', 'weight', 'diamond_date', 'price')
->with(['calculations', function($query){
     $query->select('id', 'height', 'width')
}])->first();

我搜索了很多,每个人都建议选择这种类型的数据,但我不知道为什么在我选择特定列时数据是空的。

最佳答案

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

$this->diamonds->select('id', 'image', 'number', 'weight', 'diamond_date', 'price')
     ->with(['calculations', function($query){
             $query->select('id', 'diamond_id', 'height', 'width')
      }])->first();

关于php - Laravel hasMany 关系选择特定列问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56076034/

相关文章:

php - 当 AJAX 调用时,Laravel 重定向到来自 Controller 的路由

javascript - 在 Cors 中发送原始 cookie 不适用于 VideoJS

php - Laravel Schema 设计多对多

php - PHP 中的 Z 分数到百分位数

php - 我可以在 php 中使用 glftpd 的哈希算法吗?

php - 让用户创建自己的自定义选择菜单选项,同时保持应用程序默认设置

php - 使用 symfony 上传 PDF 文件

mysql - 多个结果集的多个查询

php - Swift 我应该如何存储聊天昵称?

PHP - 正确显示 MySQL 的结果