【发布时间】:2021-03-22 15:20:27
【问题描述】:
我有 3 个模型
1 本书:
class Book extends Model
{
protected $guarded=[];
public function users(){return $this->belongsToMany(User::class);}
public function bookUser(){return $this->hasMany(BookUser::class);}
}
2 用户
class User extends Authenticatable
{
protected $guarded = [];
public function books(){return $this->belongsToMany(Book::class);}
3-bookuser
class BookUser extends Model
{
protected $guarded = [];
protected $table = 'book_user';
public function book(){return $this->belongsTo(Book::class);}
public function user(){return $this->belongsTo(User::class) ; }
}
图书用户迁移:
Schema::create('book_user', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->foreignId('book_id')->constrained();
$table->foreignId('user_id')->constrained();
$table->boolean('like')->nullable()->default(0);
});
我正在尝试获取当前用户喜欢的所有书籍:
public function index()
{
id=Auth::user()->id;
$books=Book::with('users')->get();
return response()->json($books);
}
这是我得到的:
[
{
"id": 1,
"created_at": "2021-03-22T14:16:30.000000Z",
"updated_at": "2021-03-22T14:16:30.000000Z",
"name": "power",
"image": "978014444447899.jpg",
"users": [
{
"id": 1,
"name": "mark",
"type": "reader",
"image": null,
"created_at": "2021-03-22T13:59:26.000000Z",
"updated_at": "2021-03-22T13:59:26.000000Z",
"pivot": {
"book_id": 1,
"user_id": 1,
"created_at": "2021-03-22T14:20:26.000000Z",
"updated_at": "2021-03-22T14:39:56.000000Z",
"like": 1
}
}
]
}]
我怎样才能访问数据透视表...或者如何获得呢?我正在尝试这个,但 id 不起作用
$id=Auth::user()->id;
$books=Book::with('users',function($query) {
return $query->where('user.id','=',$id);
})->get();
【问题讨论】:
标签: php laravel pivot-table eager-loading