簡體   English   中英

如何在 Laravel 5.8 中基於多對多關系查找數據

[英]How to find data based on Many To Many relationship in 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM