我在我的 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/