【问题标题】:Laravel hasMany relationship select specific column issueLaravel hasMany 关系选择特定列问题
【发布时间】:2019-09-28 06:29:41
【问题描述】:

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

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

【问题讨论】:

    标签: php mysql laravel has-many eloquent-relationship


    【解决方案1】:

    请记住,$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();
    

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 2014-08-21
      相关资源
      最近更新 更多