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();
My Answer:
>belongsToMany('App\User')->withPivot('role');}_}
2-user:
_class User extends Model_{_protected $guarded=[];_public function books(){return $this->belongsToMany('App\Book')->withPivot('role');}_}
3-pivot table:
_class BookUser extends Pivot_{_protected $guarded=[];_protected $table = 'book_user';_}
Now, if you want to access the pivot table data using eager loading, you can do so by modifying the relationship methods in your models as follows:
In the Book model:
php
public function users(){
return $this->belongsToMany('App\User')->using('App\BookUser')->withPivot('role');
}
In the User model:
php
public function books(){
return $this->belongsToMany('App\Book')->using('App\BookUser')->withPivot('role');
}
By specifying the `using('App\BookUser')` method in the relationship, you are telling Laravel to use the BookUser model as the intermediate table for the many-to-many relationship. This allows you to access the pivot table data using eager loading.
Rate this post
5 of 5 based on 3708 votesComments