在 Laravel Eloquent get() 查询中插入未定义的变量

Insert undefined variable in Laravel Eloquent get() query

我在 Laravel 中有两个模型,Laravel 用于 API。

Wallet = [name, wallet_category_id, user_id]
Wallet_Category = [id, name]

我在控制器中使用 get() 调用所有钱包,如何在我的输出中添加钱包类别名称?

Wallet::where('user_id', $request->get('user_id'))->get()

输出将像:

[
    {
        "id": 12,
        "user_id": 2,
        "name": "wallet1",
        "wallet_category_id" : 1,
        "created_at": "2020-03-09 22:40:29",
        "updated_at": "2020-03-09 22:40:29"
    },
    {
        "id": 13,
        "user_id": 2,
        "name": "wallet2",
        "wallet_category_id" : 2,
        "created_at": "2020-03-10 13:57:37",
        "updated_at": "2020-03-10 13:57:37"
    }
]

我想要这样的输出:

[
    {
        "id": 12,
        "user_id": 2,
        "name": "wallet1",
        "wallet_category_id" : 1,
        "created_at": "2020-03-09 22:40:29",
        "updated_at": "2020-03-09 22:40:29",
        "category" : "cat_1"
    },
    {
        "id": 13,
        "user_id": 2,
        "name": "wallet2",
        "wallet_category_id" : 2,
        "created_at": "2020-03-10 13:57:37",
        "updated_at": "2020-03-10 13:57:37",
        "category" : "cat_2"
    }
]

可能吗?

先谢谢了。

关系

Wallet 模型中建立关系

class Wallet extends Model
{

    public function walletcategory()
    {
        return $this->belongsTo('App\Wallet_Category','wallet_category_id','id');
    }
}

现在在控制器中

$wallets = Wallet::with('walletcategory')->where('user_id', $request->get('user_id'))->get();


foreach($wallets as $wallet){
    $wallet->walletcategory->name
}

加入

如果你想使用 join 获取它,请按照以下查询进行操作。

Wallet::select('wallet.*','wallet_category.name')->leftjoin('wallet_category','wallet_category.id','wallet.wallet_category_id')->where('wallet.user_id', $request->get('user_id'))->get();

一种方法是在检索钱包

时使用Eagar Loading钱包类别关系信息

钱包模型中创建关系

//Wallet.php

...

use App\Wallet_Category;

...

public function walletCategory(){
    return $this->belongsTo(Wallet_Category, 'wallet_category_id', 'id')
}

现在从关系中检索必要的列,如 id、名称

$wallets = Wallet::with('walletCategory:id,name')->where('user_id', $request->get('user_id'))->get();

您将能够检索 walletCategory 名称,例如:

foreach($wallets as $wallet){
    //retrieve wallet category name like 
    $wallet->walletCategory->name
}