简体   繁体   中英

Laravel 5.8: SQLSTATE[42S22]: Column not found: 1054 Unknown column

I have a table called user_wallet like this:

在此处输入图片说明

Then at the Controller, I tried this:

try {
    if ($request->pay_wallet == '1') {
        $us_id = Auth()->user()->usr_id;
        $user_wallet = UserWallet::find('user_id', $us_id);
        dd($user_wallet);
    }
}catch (\Exception $e) {
    dd($e);
}

But I get this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '2' in 'field list' (SQL: select 2 from user_wallet where user_wallet . id = user_id limit 1)

However as you can see in the picture, there are two wallets with the user_id of 2.

So what's going wrong here? How can I solve this issue?

find 方法只对id 有效,所以最好使用 where 子句

$user_wallet = UserWallet::where('user_id', $us_id);

I think you are using find() wrong, this method accepts only one paramater, it is the value of the primary key you want to find. Because you are in a pivot table and there is no id present, you will have to use firstWhere('user_id', $us_id) for the first occurrence or you will have to rewrite the find() method for the pivot table.

But please be aware that a user could have multiple wallets, so it might be better to ask them which wallet to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM