【问题标题】:How to query two tables in Laravel如何在 Laravel 中查询两个表
【发布时间】:2020-05-05 06:34:09
【问题描述】:

当用户提交表单时,我试图在 Laravel 中查询两个表。数据存储在事务表中,我还可以通过添加 $transactions->amt 和 $account->total 来更新 Account 表。

我试过这样做;

public function store(Request $request)
    {
        $account = DB::table('users')
            ->join('accounts', "users.id", '=', 'accounts.user_id')
            ->select('users.*', 'accounts.*')
            ->first();

        $transaction = new Transaction();
        $data  = $this->validate($request, [
            'baddress'=>'required',
            'package'=>'required',
            'amt'=>'required',
        ]);
        $transaction->username = $account->username;          
        $transaction->baddress = $request->input('baddress');
        $transaction->package = $request->input('package');
        $transaction->amt = $request->input('amt');
        $transaction->fund_option = "Fund";
        $transaction->save();

        $bal= $transaction->amt + $account->total;

        $account->amt_paid = $bal;
        $account->total = $bal;
        $account->save();

        return redirect('/transfer')->with('success', 'Transaction has been made');
    }

但我收到了这个错误:

调用未定义的方法 stdClass::save()

我怎样才能找到最好的方法来做到这一点?

【问题讨论】:

标签: php laravel


【解决方案1】:

出现该错误是因为 $account 不是集合。方法 save() 是模型集合中的方法。

如果你想更新,你可以使用这个代码。

$accountUpdate = DB::table('accounts')
          ->where('id', $account->id)
          ->update(['amt_paid' => $bal, 'total' => $bal]);

但是如果你想使用方法 save() 那么你必须从模型中调用 $account。

【讨论】:

    【解决方案2】:

    $account 是由您的联接(users.* 和 accounts.*)创建的行,因此它是 stdClass,而不是 Eloquent 模型。你没有 save() 方法

    为此,您应该在用户模型和帐户模型之间建立关系:

    //Account.php
    
    public function user(){
         return $this->belongsTo("App\User");
    }
    
    ........
    
    //User.php
    
    public function account(){
         return $this->hasOne("App\Account");
    }
    

    然后您可以从您的用户那里检索帐户:

    $user = User::first();
    
    $account = $user->account;
    
    [....]
    
    $account->amt_paid = $bal;
    $account->total = $bal;
    $account->save();
    

    【讨论】:

      【解决方案3】:

      你必须像这样使用。这很简单

      $accountModelUpdate = DB::table('accounts')
            ->where('user_id', $account->id)
            ->update(['amt_paid' => $bal, 'total' => $bal]);
      

      【讨论】:

        猜你喜欢
        • 2021-04-19
        • 1970-01-01
        • 2018-03-19
        • 2015-04-17
        • 2021-01-09
        • 2021-11-19
        • 1970-01-01
        • 1970-01-01
        • 2019-06-10
        相关资源
        最近更新 更多