我有两个与Eloquent Laravel相关的模型(User
和UsersDetails
)。
用“SelDetails”模型“用户”反映
public function SelDetails {
return $this->belongsTo('App\UsersDetails', 'users_id');
}
我想从SelDetails只获得两列'created_by_id','created_by_name'
UserController的
$users = User::with(['SelDetails' => function($query){
$query->select(['created_by_id', 'created_by_name']);
}])
->where('is_active', '=', 0)
->orderBy('id', 'desc')
->get();
我从User
获取数据但在SelDetails
中空白
[relations:protected] => Array
(
[SelDetails] =>
)
请指正。
各位朋友,感谢你们对这个问题的宝贵回应。我通过以下方式获得了解决方案。
“用户”模型中的更改与“SelDetails”的关系
public function SelDetails {
#return $this->belongsTo('App\UsersDetails', 'users_id');// the old one
return $this->hasOne('App\UsersDetails', 'users_id');
}
“UserController”中的更改
$users = User::with('SelDetails')->where('is_active', '=', 0)->orderBy('id', 'desc')->get();
这就是我所做的改变并得到了结果
谢谢
我可能错了,但它可能是select中的数组,试试
$query->select('created_by_id', 'created_by_name');
你尝试过类似的东西吗?
来自$users = App\Book::with('author:id,name')->get();
的the documentation?在你的情况下,它应该看起来像:
User::with('SelDetails:created_by_id,created_by_name')
->where('is_active', '=', 0)
->orderBy('id', 'desc')
->get();
with()
方法可以采用字符串(或由字符串填充的数组),例如。 relationName:column1,column2
。