我有以下的數據庫結構:如何僅在Laravel關係中選擇一些列?
用戶
- ID
- 名
後
- 編號
- user_id說明
- 標題
- 內容
所以我創建在我的模型的關係函數:
class User extends Model {
public function post()
{
return $this->hasMany(Post::class);
}
}
如果我執行$user->post
將在返回後完成的對象。
如何才能獲得帖子ID?
我有以下的數據庫結構:如何僅在Laravel關係中選擇一些列?
用戶
後
所以我創建在我的模型的關係函數:
class User extends Model {
public function post()
{
return $this->hasMany(Post::class);
}
}
如果我執行$user->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太多。
爲了得到一個ids而不是雄辯模型的列表,我將使用查詢構建器。
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;
。
友情提示:使用'posts'而不是'post'。你有很多帖子。 –