[英]How to select some columns only in Laravel relationship?
我具有以下数据库结构:
用户
发布
因此,我在模型中创建了关系函数:
class User extends Model {
public function post()
{
return $this->hasMany(Post::class);
}
}
如果我执行$user->post
将返回完整的post对象。
如何获取仅帖子ID?
你可以这样做
$user = User::with(['post' => function ($q) {
$q->select('id');
}])->where('id', $id)->first();
或者您可以设置选择您的关系
public function post()
{
return $this->hasMany(Post::class)->select(['id','user_id']);
}
您至少需要user_id才能使其正常运行。
public function post() {
return $this->hasMany(Post::class)->select(['id', 'user_id']);
}
如果您不想在特定情况下显示它; 尝试:
$user->post->each(function($post) {
$post->setVisible(['id']);
});
这样,您也可以摆脱user_id。
为了只获取ID列表而不是雄辩的模型,我将使用查询生成器。
DB::table('posts')
->select('posts.id') // fetch just post ID
->join('users', 'posts.user_id', '=', 'users.id')
->where('users.id', ...) // if you want to get posts only for particular user
->get()
->pluck('id'); // results in array of ids instead of array of objects with id property
为了使其正常工作,您需要添加use DB;
在同一文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.