我有以下表格
我有以下型号:
class User {
public function favouriteBooks()
{
return $this->belongsToMany(Book::class, 'favourite_books');
}
}
我希望获得属于用户的所有ID。
我现在这样做的方式是这样的:
$user->favouriteBooks()->select('book_id')->get();
然而,这会返回类似的数据;
[
{
"book_id": 23,
"pivot": {
"user_id": 57,
"book_id": 23
}
},
{
"book_id": 41,
"pivot": {
"user_id": 57,
"book_id": 41
}
},
...
]
我希望它能像这样返回数据:
[
23,
41,
...
]
我该怎么做?
答案 0 :(得分:12)
我建议将pivot放在隐藏数组中,如user.php:
protected $hidden = ['pivot'];
将从所有返回的json中删除枢轴。
答案 1 :(得分:4)
使用pluck()
方法:
$user->favouriteBooks()->pluck('book_id');
答案 2 :(得分:0)
或:
$user = User::where('id',1)->with('favourite_books')->first();
$fbs = [];
foreach($user->favourite_books as $book) {
$fbs[] = $book['book_id'];
}
unset($user->favourite_books);
$user->favourite_books = $fbs;
return $user;