如何在多对多关系的数据透视 table 上查找数据

How to find data on pivot table of a Many To Many relationship

我在 userswallets 之间存在多对多关系。

所以在 User.php 型号:

public function wallets()
    {
        return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
    }

并且在 Wallet.php 型号:

public function users()
    {
        return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
    }

table user_wallet 的迁移也在这里:

public function up()
    {
        Schema::create('user_wallet', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('usr_id')->on('users');
            $table->unsignedBigInteger('wallet_id');
            $table->foreign('wallet_id')->references('id')->on('wallets');
            $table->integer('balance');
            $table->timestamps();
        });
    }

现在我需要 return 基于用户 ID 和钱包 ID 的数据,如下所示:

在控制器处:

$bal = Wallet::where(['user_id' => $user_id, 'wallet_id' => $wallet_id]);

但这是错误的,因为模型 Wallet 连接到 wallets table 而不是 table user_wallet.

那么如何为这个 where 条件定义 user_wallet table?

非常感谢你们对此的任何想法或建议...

提前致谢。

我想你可以使用 whereHas

Wallet::with("users")->whereHas('users',function ($query)use($user_id){

        $query->where('user_id',$user_id);
     

    })->find($wallet_id)

Wallet::with("users")->whereHas('users',function ($query)use($user_id,$wallet_id){

        $query->where('user_id',$user_id);
        $query->where('wallet_id',$wallet_id);

    })->first()

并且钱包模型中的关系也需要更新

public function users() { 

    return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id'); 
}