【问题标题】:eager loading access the pivot table急切加载访问数据透视表
【发布时间】: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


    【解决方案1】:

    您只需要将$id 注入到具有use 的函数作用域中

    $id=Auth::user()->id;
        
    $books=Book::with(['users' => function($query) use($id) {
        $query->where('user.id','=',$id);
    }])->get();
    

    【讨论】:

    • 给我这个 TypeError: mb_strpos(): Argument #1 ($haystack) must be of string, Closure given in file
    • 我将其更改为 user_id .. 终于可以使用了!!非常感谢伙计。
    猜你喜欢
    • 2014-09-11
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多