微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Laravel 5.8 中基于多对多关系查找数据

如何解决如何在 Laravel 5.8 中基于多对多关系查找数据

我在用户模型和钱包模型之间有一个多对多的关系:

Wallet.PHP

public function users()
    {
        return $this->belongsToMany(User::class);
    }

还有User.PHP

public function wallets()
    {
        return $this->belongsToMany(Wallet::class);
    }

我有这三个与钱包相关的表格:

wallets

public function up()
    {
        Schema::create('wallets',function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('name')->unique();
            $table->tinyinteger('is_active');
            $table->tinyinteger('is_cachable');
            $table->timestamps();
        });
    }

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

和表user_wallet_transactions

public function up()
    {
        Schema::create('user_wallet_transactions',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->string('amount');
            $table->string('description');
            $table->timestamps();
        });
    }

现在我需要显示单个用户的钱包。因此,在 users.index Blade 中,我添加了以下内容

<a href="{{ route('user.wallet',$user->usr_id) }}" class="fa fa-wallet text-dark"></a>

然后像这样将用户数据发送到控制器:

public function index(User $user)
    {
        // retrieve user_wallet information
        return view('admin.wallets.user.index',compact(['user']));
    }

但我不知道如何在此方法中检索 user_wallet 信息。

那么在这种情况下如何从 user_wallet 获取数据。

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

提前致谢。

解决方法

一种方法是接受 param 作为 $id

public function index($id)

然后

User::with('wallets')->has('wallets')->find($id);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。