我发现了这个:Get Specific Columns Using “With()” Function in Laravel Eloquent,但从那里没有任何东西是没有帮助的。
我有users表,列: id、name、supplier_id。表供应商,列: id、名称。当我从Model调用relation或使用急切的约束时,relation是空的。当我注释(删除) constraint select(['id'])
时,会显示结果,但会显示所有用户字段。
$query = Supplier::with(['test_staff_id_only' => function ($query) {
//$query->where('id',8); // works only for testing https://laravel.com/docs/6.x/eloquent-relationships#constraining-eager-loads
// option 1
$query->select(['id']); // not working , no results in // "test_staff_id_only": []
// option 2
//$query->raw('select id from users'); // results with all fields from users table
}])->first();
return $query;
在供应商模型中:
public function test_staff_id_only(){
return $this->hasMany(User::class,'supplier_id','id')
//option 3 - if enabled, no results in this relation
->select(['id']);// also tried: ->selectRaw('users.id as uid from users') and ->select('users.id')
}
如何从用户中仅选择id?
发布于 2020-06-06 00:50:49
在您的关系中删除select('id')
public function test_staff_id_only(){
return $this->hasMany(User::class,'supplier_id','id');
}
现在在你的代码中:
$query = Supplier::with(['test_staff_id_only:id,supplier_id'])->first();
发布于 2020-06-06 00:29:03
实际上有一个非常简单的答案。将你们的关系定义为:
public function users(){
return $this->hasMany(User::class, 'supplier_id', 'id');
}
现在,如果调用Supplier::with('users')->get()
,您将获得所有供应商及其users
的列表,该列表很接近,但有点臃肿。要限制关系中返回的列,请使用:
修饰符:
$suppliersWithUserIds = Supplier::with('users:id')->get();
现在,您将拥有一个Supplier
型号列表,并且每个$supplier->users
值将只包含ID。
https://stackoverflow.com/questions/62219997
复制相似问题