首页 > 解决方案 > Laravel hasMany 关系选择特定列问题

问题描述

我在我的 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();

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

标签: phpmysqllaravelhas-manyeloquent-relationship

解决方案


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

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

推荐阅读