【发布时间】:2021-09-25 17:56:42
【问题描述】:
users 和 wallets 之间存在多对多关系。
所以在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