【问题标题】:How to find data on pivot table of a Many To Many relationship如何在多对多关系的数据透视表上查找数据
【发布时间】:2021-09-25 17:56:42
【问题描述】:

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');
    }

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();
        });
    }

现在我需要根据用户 ID 和钱包 ID 返回数据,如下所示:

在控制器处:

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

但这是错误的,因为模型Wallet 连接到wallets 表,而不是user_wallet 的数据透视表。

那么我该如何为这个where 条件定义user_wallet 表呢?

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

提前致谢。

【问题讨论】:

  • 根据docs,您可以定义枢轴模型,然后将其称为$userWalet = UserWalet::where(['user_id' => $userid, 'wallet_id' => $walletId])->first();
  • @Tpojka 类 'App\Http\Controllers\Wallet\UserWalet' 未找到
  • 您需要在位置app/Models/UserWallet.php 中创建UserWallet 模型并使用use App\Models\UserWallet 将其导入控制器。
  • 编辑:现在我正在检查您是否使用 5.8 版,在这种情况下,您没有 Models 目录,您的模型将位于 app/UserWallet.php 位置,并在控制器中使用 @987654344 导入@ 默认情况下。

标签: php laravel laravel-5.8


【解决方案1】:

我认为你可以使用 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'); 
} 

【讨论】:

  • 我对此进行了测试,它返回 null,但是 user_idwallet_id 存在
  • 看起来关系键是错误的,所以试试 public function users() { return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id'); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
  • 2018-09-23
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多