Reputation: 13
i have 3 models
1-book:
class Book extends Model
{
protected $guarded=[];
public function users(){return $this->belongsToMany(User::class);}
public function bookUser(){return $this->hasMany(BookUser::class);}
}
2-user
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) ; }
}
bookuser migrations:
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);
});
i am trying to get all the books with the likes of just the current user:
public function index()
{
id=Auth::user()->id;
$books=Book::with('users')->get();
return response()->json($books);
}
this is what i got:
[
{
"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
}
}
]
}]
how can i access the pivot table...or how to get that like?? am trying this but id doesn't work
$id=Auth::user()->id;
$books=Book::with('users',function($query) {
return $query->where('user.id','=',$id);
})->get();
Upvotes: 1
Views: 37
Reputation: 4271
You just need to inject the $id
to the function scope with use
$id=Auth::user()->id;
$books=Book::with(['users' => function($query) use($id) {
$query->where('user.id','=',$id);
}])->get();
Upvotes: 1