php - 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();
我搜索了很多,每个人都建议选择这种类型的数据,但我不知道为什么在选择特定列时数据为空。
解决方案
请记住,在$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();
推荐阅读
- asp.net - 如何在使用 IIS Express 在 Visual Studio 2015 中进行调试时从 CAC 获取 Request.ServerVariables("CERT_SUBJECT")
- bash - Bash - If 语句执行空比较
- angular9 - 错误:找不到模块:错误:无法解析 ***/node_modules/ng2-pdf-viewer/__ivy_ngcc__/node_modules/pdfjs-dist/build 中的“fs”
- r - 使用 dplyr::group_by() 预测每组黄土回归后的特定 x 值
- reactjs - 使用 Joi 进行输入时的密码和确认密码验证
- ios - RealmSwift:在 Swift 中使用 MongoDB Realm 实现一次登录
- excel - 使用 VBA 插入 Excel 公式时如何使用变量?
- c++ - 访问 char* 的元素并检查值 C++
- owl - 如何在 Protege 中定义求和数据值的规则?
- python - 在不使用嵌套 for 循环的情况下迭代 pandas 数据框