简体   繁体   English

Laravel 5.5:将查询构建器转换为 eloquent

[英]Laravel 5.5: Convert query builder to eloquent

Is there a way to transform this query builder to eloquent?有没有办法将这个查询构建器转换为 eloquent?

$transactions = DB::table('transactions')
    ->join('accounts', 'transactions.account_id', '=', 'accounts.id')
    ->select('transactions.*', 'accounts.name as account_name')
    ->paginate(5);

I tried it with One To Many .我用一对多尝试过。 But it need the find() function so it give me one account's transactions but I need to select all transactions with accounts.name但它需要find()函数,所以它给了我一个帐户的交易,但我需要选择所有带有 accounts.name 的交易

In comments, you've said you have one to many relationship defined (I assume it's Accounts has many Transactions) and you need to get all transactions with account name, so do this:在评论中,您已经说过您定义了一对多的关系(我假设它是 Accounts 有很多 Transactions)并且您需要使用帐户名获取所有交易,因此请执行以下操作:

Transaction::with('account')->paginate(5);

Where account is relationship: account是关系的地方:

public function account()
{
    return $this->belongsTo(Account::class);
}

Then you'll be able to display the data like this:然后你就可以像这样显示数据:

@foreach ($transactions as $transaction)
    {{ $transaction->id }}
    {{ $transaction->account->name }}
@endforeach

You will need to use models to do that.您将需要使用模型来做到这一点。

  1. Transaction model and Account model.交易模型和账户模型。

  2. Define their relationships定义他们的关系

  3. Create a method in the transaction model to retrieve the related account names.在交易模型中创建一个方法来检索相关的帐户名称。

    function accoutNames() { //blablabla } function accoutNames() { //blablabla }

  4. Do the query in controller, something like that:在控制器中执行查询,如下所示:

    Transaction->accountNames();交易->账户名();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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