1

我在 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"
    }
]

可能吗?

之前谢谢。

4

2 回答 2

1

关系

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();
于 2020-03-15T04:02:08.753 回答
0

一种方法是在检索钱包时使用Eagar 加载 钱包类别关系信息

在钱包模型中创建关系

//Wallet.php

...

use App\Wallet_Category;

...

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

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

$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
}
于 2020-03-15T04:02:29.363 回答